K-means++聚类matlab代码,附上可视化分析的代码
时间: 2024-02-12 11:08:51 浏览: 73
Matlab实现K-means++聚类
以下是K-means++聚类的MATLAB代码,包括可视化分析部分:
```matlab
% K-means++ clustering with visualization
% Generate sample data
rng(1);
X = [randn(100,2)*0.75+ones(100,2);...
randn(100,2)*0.5-ones(100,2)];
% Set number of clusters
K = 2;
% Initialize centroids using K-means++
D = pdist2(X,X,'euclidean');
[~,idx] = max(sum(D,2));
centroids = X(idx,:);
for i = 2:K
D = pdist2(X,centroids,'euclidean');
[~,idx] = min(D,[],2);
d = min(D,[],2).^2;
probs = d/sum(d);
cumprobs = cumsum(probs);
r = rand();
j = find(cumprobs>=r,1,'first');
centroids(i,:) = X(j,:);
end
% Perform K-means clustering
max_iters = 10;
for iter = 1:max_iters
D = pdist2(X,centroids,'euclidean');
[~,idx] = min(D,[],2);
for i = 1:K
centroids(i,:) = mean(X(idx==i,:),1);
end
end
% Visualize clustering
figure;
gscatter(X(:,1),X(:,2),idx);
hold on;
plot(centroids(:,1),centroids(:,2),'kx','MarkerSize',10,'LineWidth',2);
title(sprintf('K-means++ clustering with K=%d',K));
```
运行以上代码,即可得到K-means++聚类的可视化结果。
需要注意的是,以上代码中使用了`pdist2`函数计算欧几里得距离,如果您的MATLAB版本较老,可能会没有该函数。此时,您可以使用`pdist`函数代替,例如:
```matlab
D = pdist(X,'euclidean');
D = squareform(D);
```
另外,如果您需要使用其他距离度量或聚类方法,也可以在上述代码中进行相应修改。
阅读全文