【发布时间】:2023-04-03 23:45:02
【问题描述】:
我在 MATLAB 中使用 k-means。这是我的代码:
load cobat.txt; % read the file
k=input('Enter a number: '); % determine the number of cluster
isRand=0; % 0 -> sequeantial initialization
% 1 -> random initialization
[maxRow, maxCol]=size(cobat);
if maxRow<=k,
y=[m, 1:maxRow];
else
% initial value of centroid
if isRand,
p = randperm(size(cobat,1)); % random initialization
for i=1:k
c(i,:)=cobat(p(i),:) ;
end
else
for i=1:k
c(i,:)=cobat(i,:); % sequential initialization
end
end
temp=zeros(maxRow,1); % initialize as zero vector
u=0;
while 1,
d=DistMatrix3(cobat,c); % calculate the distance
[z,g]=min(d,[],2); % set the matrix g group
if g==temp, % if the iteration doesn't change anymore
break; % stop the iteration
else
temp=g; % copy the matrix to the temporary variable
end
for i=1:k
f=find(g==i);
if f % calculate the new centroid
c(i,:)=mean(cobat(find(g==i),:),1)
end
end
c
sort(c)
end
y=[cobat,g]
“cobat”是我的文件。看起来是这样的:
65 80 55
45 75 78
36 67 66
65 78 88
79 80 72
77 85 65
76 77 79
65 67 88
85 76 88
56 76 65
“c”是每个簇的质心(簇的中心)的变量。 “g”是显示簇号的变量。问题是,我想根据质心(c)对簇号(从小到大)进行排序/拟合。所以,我尝试排序(c),但它不影响簇数(g)。
当我尝试排序(g)时,它的排序不像我想要的那样。我希望根据质心对簇号进行排序。例子;当我使用 k=3 运行代码时,这里是最终的质心
73.0000 79.0000 70.6667 %C 1
58.3333 73.3333 84.6667 %C 2
36.0000 67.0000 66.0000 %C 3
当我对它进行排序时,数字簇也被“排序”了,
36.0000 67.0000 66.0000 %C 3
58.3333 73.3333 70.6667 %C 2
73.0000 79.0000 84.6667 %C 1
我想要它的数字集群是合适的,像这样。
36.0000 67.0000 66.0000 %C 1
58.3333 73.3333 70.6667 %C 2
73.0000 79.0000 84.6667 %C 3
它是合适的,没有排序,所以当运行这行 'y=[cobat,g]' 时,它也会改变。
这看起来很简单,但很棘手。我想不通。有谁有办法解决吗?
谢谢。
【问题讨论】:
标签: matlab sorting cluster-analysis k-means