质心不对应于图像中的坐标,而是对应于特征空间中的坐标。有两种方法可以测试 kmeans 的执行情况。对于这两种方式,您都希望首先将这些点与其最近的集群相关联。您可以从 kmeans 的第一个输出中获取此信息。
(1)您可以通过将6维空间缩小为2或3维空间,然后用不同颜色绘制不同分类的坐标来可视化聚类结果。
假设特征向量收集在一个名为featureArray 的数组中,并且您要求nClusters 集群,您将使用mdscale 将数据转换为3D 空间,如下所示:
%# kmeans clustering
[idx,centroids6D] = kmeans(featureArray,nClusters);
%# find the dissimilarity between features in the array for mdscale.
%# Add the cluster centroids to the points, so that they get transformed by mdscale as well.
%# I assume that you use Euclidean distance.
dissimilarities = pdist([featureArray;centroids6D]);
%# transform onto 3D space
transformedCoords = mdscale(dissimilarities,3);
%# create colormap with nClusters colors
cmap = hsv(nClusters);
%# loop to plot
figure
hold on,
for c = 1:nClusters
%# plot the coordinates
currentIdx = find(idx==c);
plot3(transformedCoords(currentIdx,1),transformedCoords(currentIdx,2),...
transformedCoords(currentIdx,3),'.','Color',cmap(c,:));
%# plot the cluster centroid with a black-edged square
plot3(transformedCoords(1:end-nClusters+c,1),transformedCoords(1:end-nClusters+c,2),...
transformedCoords(1:end-nClusters+c,3),'s','MarkerFaceColor',cmap(c,:),...
MarkerEdgeColor','k');
end
(2) 或者,您可以创建一个伪彩色图像,显示图像的哪一部分属于哪个集群
假设你有nRows by nCols 块,你写
%# kmeans clustering
[idx,centroids6D] = kmeans(featureArray,nClusters);
%# create image
img = reshape(idx,nRows,nCols);
%# create colormap
cmap = hsv(nClusters);
%# show the image and color according to clusters
figure
imshow(img,[])
colormap(cmap)