谱聚类--SpectralClustering

谱聚类一般会先对两两样本间求相似度, 然后根据相似度矩阵求出拉普拉斯矩阵,然后将每个样本映射到拉普拉斯矩阵特诊向量中,最后使用k-means聚类。

scikit-learn开源包中已经有现成的接口可以使用,具体见

http://scikit-learn.org/dev/modules/generated/sklearn.cluster.SpectralClustering.html#sklearn.cluster.SpectralClustering

写了一个测试例子

构造二维空间样本点,

#!/usr/bin/env python
import random
import numpy as np
import math

index = 0
pointlist = []
fd = open("points.txt", 'w')

for x in np.arange(0.1, 10., 0.5) :
    for y in np.arange(0., 10., 0.1) :
        print >> fd, str(index)+'\t'+str(x)+'\t'+str(y)
        pointlist.append((index, (x, y)))
        index += 1

for x in np.arange(-10.0, -0.1, 0.5) :
    for y in np.arange(0., 10., 0.1) :
        print >> fd, str(index)+'\t'+str(x)+'\t'+str(y)
        pointlist.append((index, (x, y)))
        index += 1

for x in np.arange(-10.0, -0.1, 0.5) :
    for y in np.arange(-10.0, 0., 0.1) :
        print >> fd, str(index)+'\t'+str(x)+'\t'+str(y)
        pointlist.append((index, (x, y)))
        index += 1
fd.close()

def get_dist(pnt1, pnt2) :
    return math.sqrt((pnt1[1][0] - pnt2[1][0])**2 + (pnt1[1][1] - pnt2[1][1])**2)

simfd = open("sim_pnts.txt", 'w')
for pnt1 in pointlist :
    for pnt2 in pointlist :
        index1, index2 = pnt1[0], pnt2[0]
        dist = get_dist(pnt1, pnt2)
        if dist <=0.00001 :
            print >> simfd, str(index1) + "\t"+str(index2) + "\t" + "10"
            continue
        sim = 1.0 / dist
        print >> simfd, str(index1) + "\t"+str(index2) + "\t" + str(sim)
simfd.close()

使用谱聚类:

#!/usr/bin/env python
# Authors:  Emmanuelle Gouillart <[email protected]>
#           Gael Varoquaux <[email protected]>
# License: BSD 3 clause

import sys
import numpy as np

from sklearn.cluster import spectral_clustering
from scipy.sparse import coo_matrix

###############################################################################

fid2fname = {}
for line in open("points.txt") :
    line = line.strip().split('\t')
    fid2fname.setdefault(int(line[0]), (float(line[1]), float(line[2])))

N = len(fid2fname)
rowlist = []
collist = []
datalist = []
for line in open("sim_pnts.txt") :
    line = line.strip().split('\t')
    if len(line) < 3 : continue
    f1, f2, sim = line[:3]
    rowlist.append(int(f1))
    collist.append(int(f2))
    datalist.append(float(sim))

for id in fid2fname :
    rowlist.append(int(id))
    collist.append(int(id))
    datalist.append(1.0)

row = np.array(rowlist)
col = np.array(collist)
data = np.array(datalist)
graph = coo_matrix((data, (row, col)), shape=(N, N))

###############################################################################

# Force the solver to be arpack, since amg is numerically
# unstable on this example
labels = spectral_clustering(graph, n_clusters=3, eigen_solver='arpack')

#print labels
cluster2fid = {}
for index, lab in enumerate(labels) :
    cluster2fid.setdefault(lab, [])
    cluster2fid[lab].append(index)

for index, lab in enumerate(cluster2fid) :
    fd = open("cluster_%s" % index, "w")
    for fid in cluster2fid[lab] :
        print >> fd , fid2fname[fid]

将聚类后的样本可视化:

#!/usr/bin/env python
import matplotlib.pyplot as plt

plt.figure(figsize=(12,6))

cluster_list = []

cluster_0_x = []
cluster_0_y = []
for line in open("cluster_0"):
    line = line.strip().split(',')
    x = float(line[0][1:].strip())
    y = float(line[1][:-1].strip())
    cluster_0_x.append(x)
    cluster_0_y.append(y)

plt.plot(cluster_0_x, cluster_0_y, 'or')

cluster_1_x = []
cluster_1_y = []
for line in open("cluster_1"):
    line = line.strip().split(',')
    x = float(line[0][1:].strip())
    y = float(line[1][:-1].strip())
    cluster_1_x.append(x)
    cluster_1_y.append(y)

plt.plot(cluster_1_x, cluster_1_y, 'xb')

cluster_2_x = []
cluster_2_y = []
for line in open("cluster_2"):
    line = line.strip().split(',')
    x = float(line[0][1:].strip())
    y = float(line[1][:-1].strip())
    cluster_2_x.append(x)
    cluster_2_y.append(y)

plt.plot(cluster_2_x, cluster_2_y, '+g')

plt.show()

不同颜色代表不同的聚类, 可以看到聚类效果还是不错的。

时间: 2024-08-11 01:15:09

谱聚类--SpectralClustering的相关文章

用scikit-learn学习谱聚类

在谱聚类(spectral clustering)原理总结中,我们对谱聚类的原理做了总结.这里我们就对scikit-learn中谱聚类的使用做一个总结. 1. scikit-learn谱聚类概述 在scikit-learn的类库中,sklearn.cluster.SpectralClustering实现了基于Ncut的谱聚类,没有实现基于RatioCut的切图聚类.同时,对于相似矩阵的建立,也只是实现了基于K邻近法和全连接法的方式,没有基于$\epsilon$-邻近法的相似矩阵.最后一步的聚类方

谱聚类python实践

聚类后: # -*- coding: utf-8 -*-"""Created on 09 05 2017 @author: similarface"""import numpy as npimport matplotlib.pyplot as pltimport mpl_toolkits.mplot3d.axes3d as p3from sklearn import datasetsfrom sklearn import metricsfrom

聚类分析之谱聚类

聚类根据给定的样本数据集定义一个描述成对数据点相似度的亲合矩阵,并且计算矩阵的特征值和特征向量 , 然后选择合适 的特征向量聚类不同的数据点. 谱聚类可以在任意形状的样本空间聚类,且收敛于全局最优解,因此在处理高维数据方面存在着明显优势.总的来说,该算法存在一些不足之处.算法在聚类之前需要设置具体应用的尺度参数,通常需要一些经验.初始聚类中心对整个聚类效果影响很大,存在初始值敏感问题.很难找到图划分的优化解,聚类数目对于整个聚类效果有很大影响. setp1:计算图的拉普拉斯矩阵L=D-w set

利用谱聚类算法解决非完全图的聚类

在处理非完全图的聚类时候,很难找到一个有效的聚类算法去做聚类. 对于下图来说,10号点和15号点的位置相隔并不是那么近,如用普通聚类算法对下图做聚类,通常会把10号点和15号点聚在一个类上,所以一般的聚类效果并没有那么好. 而谱聚类,就很能很好的处理这类问题. 下面我们来重点介绍谱聚类 谱聚类(SpectralClustering),就是要把样本合理地分成两份或者K份.从图论的角度来说,谱聚类的问题就相当于一个图的分割问题.即给定一个图G = (V, E),顶点集V表示各个样本,带权的边表示各个

关于谱聚类的ng算法的实现

广义上讲,任何在学习过程中应用到矩阵特征值分解的方法均叫做谱学习方法,比如主成分分析(PCA),线性判别成分分析(LDA),流形学习中的谱嵌入方法,谱聚类等等. 由于科苑向世明老师课件上面关于ng的谱聚类算法里面与ng大神的论文中写到的算法中有所出入,导致昨天晚上调了一晚上的算法并没有调出满意的结果,今天在网上找到了ng大神的原始paper阅读一遍,虽然还是有很多不理解的地方,还是有了自己的见解.下面是ng算法的流程. 算法第一步先通过高斯函数计算出每个点与其他点的亲和度,与自己的亲和度为0,对

谱聚类算法

转载自:[聚类算法]谱聚类(Spectral Clustering) 1.问题描述 谱聚类(Spectral Clustering, SC)是一种基于图论的聚类方法——将带权无向图划分为两个或两个以上的最优子图(sub-Graph),使子图内部尽量相似,而子图间距离尽量距离较远,以达到常见的聚类的目的. 对于图的相关定义如下: 对于无向图G = (V,E),V表示顶点集合,即样本集合,即一个顶点为一个样本:E表示边集合. 设样本数为n,即顶点数为n. 权重矩阵:W,为n*n的矩阵,其值wi,j为

谱聚类算法及其代码(Spectral Clustering)

简介 文章将介绍谱聚类(spectral clustering)的基本算法,以及在matlab下的代码实现.介绍内容将包括: 从图分割角度直观理解谱聚类 谱聚类算法步骤 数据以及实现代码 本文将不会涉及细节化的证明和推导,如有兴趣可参考july大神的文章从拉普拉斯矩阵说到谱聚类. 对谱聚类的理解 这一节将从图分割聚类的角度直观理解谱聚类.不过,因为本人是从事社交媒体分析的,将从一种社会关系网络的角度来介绍网络图分割成多个子图的概念. 图的分割 首先将社会关系网络看成是一个整体,每一个个体(use

谱聚类算法(Spectral Clustering)

谱聚类(Spectral Clustering, SC)是一种基于图论的聚类方法——将带权无向图划分为两个或两个以上的最优子图,使子图内部尽量相似,而子图间距离尽量距离较远,以达到常见的聚类的目的.其中的最优是指最优目标函数不同,可以是割边最小分割——如图1的Smallest cut(如后文的Min cut), 也可以是分割规模差不多且割边最小的分割——如图1的Best cut(如后文的Normalized cut). 图1 谱聚类无向图划分——Smallest cut和Best cut 这样,

谱聚类(Spectral Clustering, SC)

谱聚类(Spectral Clustering, SC)是一种基于图论的聚类方法——将带权无向图划分为两个或两个以上的最优子图,使子图内部尽量相似,而子图间距离尽量距离较远,以达到常见的聚类的目 的.其中的最优是指最优目标函数不同,可以是割边最小分割——如图1的Smallest cut(如后文的Min cut), 也可以是分割规模差不多且割边最小的分割——如图1的Best cut(如后文的Normalized cut). 图1 谱聚类无向图划分——Smallest cut和Best cut 这样