2016-02-17 75 views
-1

在MATLAB中我們如何找出k-均值聚類中每個聚類的質心。數據在本質上是非常不同的。因此,我想寫一些MATLAB代碼來繪製每個簇的質心,並給出每個質心的座標。 我用下面的代碼clustering-MATLAB中的k均值聚類代碼

figure 
plot(X(:,1),X(:,2),'.') 
opts=statset('Display','final') 
[idx,c]=kmeans(x,4,'Distance','cityblock,... 
     'Replicates',5,'Options',opts) 
figure 
plot(X(idx==1,1),X(idx==1,2),'r.','MarkerSize',12) 
hold on 
plot(X(idx==2,1),X(idx==2,2),'b.','MarkerSize',12) 
hold on 
plot(X(idx==3,1),X(idx==3,2),'g.','MarkerSize',12) 
hold on 
plot(X(idx==4,1),X(idx==4,2),'y.','MarkerSize',12) 
hold on 
plot(C(:,1),C(:,2),'Kx',... 
    'MarkerSize',15,'LineWidth',3) 
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Centroids',... 
    'Location','NW') 
title 'Cluster Assignments and centroids ' 
hold off 
+0

你的代碼有什麼問題?你需要什麼樣的幫助? – Anton

+0

請不要一再提出同樣的問題! –

+0

請更新您的原始問題而不是創建新問題。改進它,你可能會收到答案。 [問] – Daniel

回答

0

我修改您的代碼位:

rng default; % For reproducibility 
X = [randn(100,2)*0.75+ones(100,2); 
    randn(100,2)*0.5-ones(100,2)]; 

opts=statset('Display','final'); 
[idx,C]=kmeans(X,4,'Distance','cityblock','Replicates',5,'Options',opts); 

plot(X(idx==1,1),X(idx==1,2),'r.','MarkerSize',12); 
hold on; 
plot(X(idx==2,1),X(idx==2,2),'b.','MarkerSize',12); 
plot(X(idx==3,1),X(idx==3,2),'g.','MarkerSize',12); 
plot(X(idx==4,1),X(idx==4,2),'y.','MarkerSize',12); 

plot(C(:,1),C(:,2),'Kx','MarkerSize',15,'LineWidth',3); 
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Centroids', 'Location','NW'); 
title('Cluster Assignments and centroids'); 
hold off; 

for i=1:size(C, 1) 
    display(['Centroid ', num2str(i), ': X1 = ', num2str(C(i, 1)), '; X2 = ', num2str(C(i, 2))]); 
end 

這裏的情節:

enter image description here

這裏是重心:

Centroid 1: X1 = 1.3661; X2 = 1.7232 
Centroid 2: X1 = -1.015; X2 = -1.053 
Centroid 3: X1 = 1.6565; X2 = 0.36376 
Centroid 4: X1 = 0.35134; X2 = 0.85358