京公网安备 11010802034615号
经营许可证编号:京B2-20210330
简单易学的机器学习算法—谱聚类(Spectal Clustering)
一、复杂网络中的一些基本概念
1、复杂网络的表示
在复杂网络的表示中,复杂网络可以建模成一个图
,其中,V表示网络中的节点的集合,E表示的是连接的集合。在复杂网络中,复杂网络可以是无向图、有向图、加权图或者超图。
2、网络簇结构
网络簇结构(network cluster structure)也称为网络社团结构(network community structure),是复杂网络中最普遍和最重要的拓扑属性之一。网络簇是整个网络中的稠密连接分支,具有同簇内部节点之间相互连接密集,不同簇的节点之间相互连接稀疏的特征。
3、复杂网络的分类
复杂网络主要分为:随机网络,小世界网络和无标度网络。
二、谱方法介绍
1、谱方法的思想
在谱聚类中定义了“截”函数的概念,当一个网络被划分成为两个子网络时,“截”即指子网间的连接密度。谱聚类的目的就是要找到一种合理的分割,使得分割后形成若干子图,连接不同的子图的边的权重尽可能低,即“截”最小,同子图内的边的权重尽可能高。
2、“截”函数的具体表现形式
“截”表示的是子网间的密度,即边比较少。以二分为例,将图聚类成两个类:S类和T类。假设用
来表示图的划分,我们需要的结果为:
其中
表示的是类别S和T之间的权重。对于K个不同的类别
,优化的目标为:
3、基本“截”函数的弊端
对于上述的“截”函数,最终会导致不好的分割,如二分类问题:
上述的“截”函数通常会将图分割成一个点和其余n-1个点。
4、其他的“截”函数的表现形式
足够大,则提出了
或者
:

其中
表示A类中包含的顶点的数目
三、Laplacian矩阵
1、Laplacian矩阵的定义
,其Laplacian矩阵定义为:

其中,d为图的度矩阵,a为图的邻接矩阵。
2、度矩阵的定义
对于一个有n个顶点的图
,其邻接矩阵为:

其中
。
3、Laplacian矩阵的性质
Laplacian矩阵;L是对称半正定矩阵;
性质3的证明:
4、不同的Laplacian矩阵
四、Laplacian矩阵与谱聚类中的优化函数的关系
1、由Laplacian矩阵到“截”函数
对于二个类别的聚类问题,优化的目标函数为:
,且

,则
其中,
表示的是顶点的数目,对于确定的图来说是个常数。由上述的推导可知,由
推导出了
,由此可知:Laplacian矩阵与有优化的目标函数
之间存在密切的联系。
2、新的目标函数
由上式可得:
是个常数,故要求
的最小值,即求
的最小值。则新的目标函数为:
其中
3、转化到Laplacian矩阵的求解


,则
,上式可以转化为:

五、从二类别聚类到多类别聚类1、二类别聚类
2、多类别聚类
基于以上的分析,谱聚类的基本过程为:
对于给定的图
,求图的度矩阵d和邻接矩阵a;
计算图的Laplacian矩阵
;
对Laplacian矩阵进行特征值分解,取其前k个特征值对应的特征向量,构成
的特征向量矩阵;
利用K-Means聚类算法对上述的
的特征向量矩阵进行聚类,每一行代表一个样本点。
2、利用相似度矩阵的构造方法


[python] view plain copy 在CODE上查看代码片派生到我的代码片
#coding:UTF-8
'''''
Created on 2015年5月12日
@author: zhaozhiyong
'''
from __future__ import division
import scipy.io as scio
from scipy import sparse
from scipy.sparse.linalg.eigen import arpack#这里只能这么做,不然始终找不到函数eigs
from numpy import *
def spectalCluster(data, sigma, num_clusters):
print "将邻接矩阵转换成相似矩阵"
#先完成sigma != 0
print "Fixed-sigma谱聚类"
data = sparse.csc_matrix.multiply(data, data)
data = -data / (2 * sigma * sigma)
S = sparse.csc_matrix.expm1(data) + sparse.csc_matrix.multiply(sparse.csc_matrix.sign(data), sparse.csc_matrix.sign(data))
#转换成Laplacian矩阵
print "将相似矩阵转换成Laplacian矩阵"
D = S.sum(1)#相似矩阵是对称矩阵
D = sqrt(1 / D)
n = len(D)
D = D.T
D = sparse.spdiags(D, 0, n, n)
L = D * S * D
#求特征值和特征向量
print "求特征值和特征向量"
vals, vecs = arpack.eigs(L, k=num_clusters,tol=0,which="LM")
# 利用k-Means
print "利用K-Means对特征向量聚类"
#对vecs做正规化
sq_sum = sqrt(multiply(vecs,vecs).sum(1))
m_1, m_2 = shape(vecs)
for i in xrange(m_1):
for j in xrange(m_2):
vecs[i,j] = vecs[i,j]/sq_sum[i]
myCentroids, clustAssing = kMeans(vecs, num_clusters)
for i in xrange(shape(clustAssing)[0]):
print clustAssing[i,0]
def randCent(dataSet, k):
n = shape(dataSet)[1]
centroids = mat(zeros((k,n)))#create centroid mat
for j in range(n):#create random cluster centers, within bounds of each dimension
minJ = min(dataSet[:,j])
rangeJ = float(max(dataSet[:,j]) - minJ)
centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
return centroids
def distEclud(vecA, vecB):
return sqrt(sum(power(vecA - vecB, 2))) #la.norm(vecA-vecB)
def kMeans(dataSet, k):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))#create mat to assign data points to a centroid, also holds SE of each point
centroids = randCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):#for each data point assign it to the closest centroid
minDist = inf; minIndex = -1
for j in range(k):
distJI = distEclud(centroids[j,:],dataSet[i,:])
if distJI < minDist:
minDist = distJI; minIndex = j
if clusterAssment[i,0] != minIndex: clusterChanged = True
clusterAssment[i,:] = minIndex,minDist**2
#print centroids
for cent in range(k):#recalculate centroids
ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster
centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean
return centroids, clusterAssment
if __name__ == '__main__':
# 导入数据集
matf = 'E://data_sc//corel_50_NN_sym_distance.mat'
dataDic = scio.loadmat(matf)
data = dataDic['A']
# 谱聚类的过程
spectalCluster(data, 20, 18)
2、网上提供的一个Matlab代码
[plain] view plain copy 在CODE上查看代码片派生到我的代码片
function [cluster_labels evd_time kmeans_time total_time] = sc(A, sigma, num_clusters)
%SC Spectral clustering using a sparse similarity matrix (t-nearest-neighbor).
%
% Input : A : N-by-N sparse distance matrix, where
% N is the number of data
% sigma : sigma value used in computing similarity,
% if 0, apply self-tunning technique
% num_clusters : number of clusters
%
% Output : cluster_labels : N-by-1 vector containing cluster labels
% evd_time : running time for eigendecomposition
% kmeans_time : running time for k-means
% total_time : total running time
%
% Convert the sparse distance matrix to a sparse similarity matrix,
% where S = exp^(-(A^2 / 2*sigma^2)).
% Note: This step can be ignored if A is sparse similarity matrix.
%
disp('Converting distance matrix to similarity matrix...');
tic;
n = size(A, 1);
if (sigma == 0) % Selftuning spectral clustering
% Find the count of nonzero for each column
disp('Selftuning spectral clustering...');
col_count = sum(A~=0, 1)';
col_sum = sum(A, 1)';
col_mean = col_sum ./ col_count;
[x y val] = find(A);
A = sparse(x, y, -val.*val./col_mean(x)./col_mean(y)./2);
clear col_count col_sum col_mean x y val;
else % Fixed-sigma spectral clustering
disp('Fixed-sigma spectral clustering...');
A = A.*A;
A = -A/(2*sigma*sigma);
end
% Do exp function sequentially because of memory limitation
num = 2000;
num_iter = ceil(n/num);
S = sparse([]);
for i = 1:num_iter
start_index = 1 + (i-1)*num;
end_index = min(i*num, n);
S1 = spfun(@exp, A(:,start_index:end_index)); % sparse exponential func
S = [S S1];
clear S1;
end
clear A;
toc;
%
% Do laplacian, L = D^(-1/2) * S * D^(-1/2)
%
disp('Doing Laplacian...');
D = sum(S, 2) + (1e-10);
D = sqrt(1./D); % D^(-1/2)
D = spdiags(D, 0, n, n);
L = D * S * D;
clear D S;
time1 = toc;
%
% Do eigendecomposition, if L =
% D^(-1/2) * S * D(-1/2) : set 'LM' (Largest Magnitude), or
% I - D^(-1/2) * S * D(-1/2): set 'SM' (Smallest Magnitude).
%
disp('Performing eigendecomposition...');
OPTS.disp = 0;
[V, val] = eigs(L, num_clusters, 'LM', OPTS);
time2 = toc;
%
% Do k-means
%
disp('Performing kmeans...');
% Normalize each row to be of unit length
sq_sum = sqrt(sum(V.*V, 2)) + 1e-20;
U = V ./ repmat(sq_sum, 1, num_clusters);
clear sq_sum V;
cluster_labels = k_means(U, [], num_clusters);
total_time = toc;
%
% Calculate and show time statistics
%
evd_time = time2 - time1
kmeans_time = total_time - time2
total_time
disp('Finished!');
[plain] view plain copy 在CODE上查看代码片派生到我的代码片
function cluster_labels = k_means(data, centers, num_clusters)
%K_MEANS Euclidean k-means clustering algorithm.
%
% Input : data : N-by-D data matrix, where N is the number of data,
% D is the number of dimensions
% centers : K-by-D matrix, where K is num_clusters, or
% 'random', random initialization, or
% [], empty matrix, orthogonal initialization
% num_clusters : Number of clusters
%
% Output : cluster_labels : N-by-1 vector of cluster assignment
%
% Reference: Dimitrios Zeimpekis, Efstratios Gallopoulos, 2006.
% http://scgroup.hpclab.ceid.upatras.gr/scgroup/Projects/TMG/
%
% Parameter setting
%
iter = 0;
qold = inf;
threshold = 0.001;
%
% Check if with initial centers
%
if strcmp(centers, 'random')
disp('Random initialization...');
centers = random_init(data, num_clusters);
elseif isempty(centers)
disp('Orthogonal initialization...');
centers = orth_init(data, num_clusters);
end
%
% Double type is required for sparse matrix multiply
%
data = double(data);
centers = double(centers);
%
% Calculate the distance (square) between data and centers
%
n = size(data, 1);
x = sum(data.*data, 2)';
X = x(ones(num_clusters, 1), :);
y = sum(centers.*centers, 2);
Y = y(:, ones(n, 1));
P = X + Y - 2*centers*data';
%
% Main program
%
while 1
iter = iter + 1;
% Find the closest cluster for each data point
[val, ind] = min(P, [], 1);
% Sum up data points within each cluster
P = sparse(ind, 1:n, 1, num_clusters, n);
centers = P*data;
% Size of each cluster, for cluster whose size is 0 we keep it empty
cluster_size = P*ones(n, 1);
% For empty clusters, initialize again
zero_cluster = find(cluster_size==0);
if length(zero_cluster) > 0
disp('Zero centroid. Initialize again...');
centers(zero_cluster, :)= random_init(data, length(zero_cluster));
cluster_size(zero_cluster) = 1;
end
% Update centers
centers = spdiags(1./cluster_size, 0, num_clusters, num_clusters)*centers;
% Update distance (square) to new centers
y = sum(centers.*centers, 2);
Y = y(:, ones(n, 1));
P = X + Y - 2*centers*data';
% Calculate objective function value
qnew = sum(sum(sparse(ind, 1:n, 1, size(P, 1), size(P, 2)).*P));
mesg = sprintf('Iteration %d:\n\tQold=%g\t\tQnew=%g', iter, full(qold), full(qnew));
disp(mesg);
% Check if objective function value is less than/equal to threshold
if threshold >= abs((qnew-qold)/qold)
mesg = sprintf('\nkmeans converged!');
disp(mesg);
break;
end
qold = qnew;
end
cluster_labels = ind';
%-----------------------------------------------------------------------------
function init_centers = random_init(data, num_clusters)
%RANDOM_INIT Initialize centroids choosing num_clusters rows of data at random
%
% Input : data : N-by-D data matrix, where N is the number of data,
% D is the number of dimensions
% num_clusters : Number of clusters
%
% Output: init_centers : K-by-D matrix, where K is num_clusters
rand('twister', sum(100*clock));
init_centers = data(ceil(size(data, 1)*rand(1, num_clusters)), :);
function init_centers = orth_init(data, num_clusters)
%ORTH_INIT Initialize orthogonal centers for k-means clustering algorithm.
%
% Input : data : N-by-D data matrix, where N is the number of data,
% D is the number of dimensions
% num_clusters : Number of clusters
%
% Output: init_centers : K-by-D matrix, where K is num_clusters
%
% Find the num_clusters centers which are orthogonal to each other
%
Uniq = unique(data, 'rows'); % Avoid duplicate centers
num = size(Uniq, 1);
first = ceil(rand(1)*num); % Randomly select the first center
init_centers = zeros(num_clusters, size(data, 2)); % Storage for centers
init_centers(1, :) = Uniq(first, :);
Uniq(first, :) = [];
c = zeros(num-1, 1); % Accumalated orthogonal values to existing centers for non-centers
% Find the rest num_clusters-1 centers
for j = 2:num_clusters
c = c + abs(Uniq*init_centers(j-1, :)');
[minimum, i] = min(c); % Select the most orthogonal one as next center
init_centers(j, :) = Uniq(i, :);
Uniq(i, :) = [];
c(i) = [];
end
clear c Uniq;
个人的一点认识:谱聚类的过程相当于先进行一个非线性的降维,然后在这样的低维空间中再利用聚类的方法进行聚类。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
数据分析的核心价值在于用数据驱动决策,而指标作为数据的“载体”,其选取的合理性直接决定分析结果的有效性。选对指标能精准定 ...
2026-01-23在MySQL查询编写中,我们习惯按“SELECT → FROM → WHERE → ORDER BY”的语法顺序组织语句,直觉上认为代码顺序即执行顺序。但 ...
2026-01-23数字化转型已从企业“可选项”升级为“必答题”,其核心本质是通过数据驱动业务重构、流程优化与模式创新,实现从传统运营向智能 ...
2026-01-23CDA持证人已遍布在世界范围各行各业,包括世界500强企业、顶尖科技独角兽、大型金融机构、国企事业单位、国家行政机关等等,“CDA数据分析师”人才队伍遵守着CDA职业道德准则,发挥着专业技能,已成为支撑科技发展的核心力量。 ...
2026-01-22在数字化时代,企业积累的海量数据如同散落的珍珠,而数据模型就是串联这些珍珠的线——它并非简单的数据集合,而是对现实业务场 ...
2026-01-22在数字化运营场景中,用户每一次点击、浏览、交互都构成了行为轨迹,这些轨迹交织成海量的用户行为路径。但并非所有路径都具备业 ...
2026-01-22在数字化时代,企业数据资产的价值持续攀升,数据安全已从“合规底线”升级为“生存红线”。企业数据安全管理方法论以“战略引领 ...
2026-01-22在SQL数据分析与业务查询中,日期数据是高频处理对象——订单创建时间、用户注册日期、数据统计周期等场景,都需对日期进行格式 ...
2026-01-21在实际业务数据分析中,单一数据表往往无法满足需求——用户信息存储在用户表、消费记录在订单表、商品详情在商品表,想要挖掘“ ...
2026-01-21在数字化转型浪潮中,企业数据已从“辅助资源”升级为“核心资产”,而高效的数据管理则是释放数据价值的前提。企业数据管理方法 ...
2026-01-21在数字化商业环境中,数据已成为企业优化运营、抢占市场、规避风险的核心资产。但商业数据分析绝非“堆砌数据、生成报表”的简单 ...
2026-01-20定量报告的核心价值是传递数据洞察,但密密麻麻的表格、复杂的计算公式、晦涩的数值罗列,往往让读者望而却步,导致核心信息被淹 ...
2026-01-20在CDA(Certified Data Analyst)数据分析师的工作场景中,“精准分类与回归预测”是高频核心需求——比如预测用户是否流失、判 ...
2026-01-20在建筑工程造价工作中,清单汇总分类是核心环节之一,尤其是针对楼梯、楼梯间这类包含多个分项工程(如混凝土浇筑、钢筋制作、扶 ...
2026-01-19数据清洗是数据分析的“前置必修课”,其核心目标是剔除无效信息、修正错误数据,让原始数据具备准确性、一致性与可用性。在实际 ...
2026-01-19在CDA(Certified Data Analyst)数据分析师的日常工作中,常面临“无标签高维数据难以归类、群体规律模糊”的痛点——比如海量 ...
2026-01-19在数据仓库与数据分析体系中,维度表与事实表是构建结构化数据模型的核心组件,二者如同“骨架”与“血肉”,协同支撑起各类业务 ...
2026-01-16在游戏行业“存量竞争”的当下,玩家留存率直接决定游戏的生命周期与商业价值。一款游戏即便拥有出色的画面与玩法,若无法精准识 ...
2026-01-16为配合CDA考试中心的 2025 版 CDA Level III 认证新大纲落地,CDA 网校正式推出新大纲更新后的第一套官方模拟题。该模拟题严格遵 ...
2026-01-16在数据驱动决策的时代,数据分析已成为企业运营、产品优化、业务增长的核心工具。但实际工作中,很多数据分析项目看似流程完整, ...
2026-01-15