├── README.md └── SpectralClustering.m /README.md: -------------------------------------------------------------------------------- 1 | SpectralClustering 2 | ================== 3 | 4 | Spectral Clustering based on Random Walk (Normalized Laplacian Matrix) 5 | -------------------------------------------------------------------------------- /SpectralClustering.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | %Spectral Clustering based on Random Walk (Normalized laplacian Matrix) 3 | %Input : 4 | %affinity : n*n matrix define the similarities between each instance in the 5 | % data 6 | %K (optional) : K Expected clusters. (If it's not provided, clustering will 7 | % be based on Eigenvalues 8 | % 9 | %Output : 10 | %KEigenVectors : The K eigenvectors that can be used to cluster all the 11 | %data 12 | %For example you can use it this way: 13 | % KEigenVectors = SpectralClustering(affinity,K) 14 | % [IDX,C] = kmeans(KEigenVectors,K) 15 | % %Where IDX contains the cluster indices of each instance. 16 | 17 | function [KEigenVectors]= SpectralClustering(affinity,K) 18 | 19 | sz = size(affinity,1); 20 | D = zeros(sz,sz); 21 | for i=1:sz 22 | D(i,i) = sum(affinity(i,:)); 23 | end 24 | 25 | L = D - affinity; 26 | [eigVec, eigVal] = eig( inv(D) * L); 27 | 28 | cEigVal = circshift(diag(eigVal),1); 29 | [~, idx] = max(cEigVal - diag(eigVal)); 30 | if ~exist('K','var') 31 | KEigenVectors = eigVec(:,idx:size(eigVec,1)-1); 32 | else 33 | KEigenVectors = eigVec(:,size(eigVec,1)-K:size(eigVec,1)-1); 34 | end 35 | end 36 | --------------------------------------------------------------------------------