聚类分析k-means代码

function spectral_cluster() %% Generate sample data points_per_cluster = 500; num_cluster = 3; bandwidth = 0.1;

data = zeros([num_cluster*points_per_cluster, 2]); index = 1;

for k = 1 : num_cluster for n = 1 : points_per_cluster theta = 2 * pi * rand;

rho = k + randn(1) * bandwidth; [x, y] = pol2cart(theta, rho); data(index,:) = [x, y]; index = index + 1; end end

%% Kmeans

mincenter = kmeans(data, num_cluster); group1 = (mincenter == 1); group2 = (mincenter == 2); group3 = (mincenter == 3); figure; hold on;

plot(data(group1,1), data(group1,2), 'r.'); plot(data(group2,1), data(group2,2), 'b.'); plot(data(group3,1), data(group3,2), 'y.'); axis square; grid on; hold off;

%% Spectral Clustering sigma = 0.1;

s1s2 = -2 * data * (data'); ss = sum(data.^2,2);

% similarity matrix (vectorlized)

% s(x_i, x_j) = exp(-|x_i - x_j|^2 /(2 * sigma^2))

A = exp( -(s1s2 + repmat(ss, 1, length(ss)) + repmat(ss', length(ss), 1))/(2*sigma^2)); D = diag(sum(A')); L = D - A;

[X, ~] = eigs(L, num_cluster, 'SM');

Y = X ./ repmat(sqrt(sum(X.^2, 2)), 1, num_cluster); mincenter = kmeans(Y, num_cluster); group1 = (mincenter == 1); group2 = (mincenter == 2); group3 = (mincenter == 3); figure; hold on;

plot(data(group1,1), data(group1,2), 'r.'); plot(data(group2,1), data(group2,2), 'b.'); plot(data(group3,1), data(group3,2), 'y.'); axis square; grid on; hold off; end

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4