对如下的二维模式样本集,编写matlab程序, X1=(0.5,0.5)T ,X2=(1,0.5)T ,X3=(1,0)T ,X4=(1,1)T X5=(5, 5)T ,X6=(6,5.5)T ,X7=(6,6)T X8=(7,0)T ,X9=(6,0.5)T ,X10=(7,-1)T ,X11=(8,-0.5)T ,用C均值聚类算法进行聚类,并作图显示,通过分别改变类别数量和初始聚类中心(控制变量法)来获得不同的结果
时间: 2024-02-21 21:00:49 浏览: 60
以下是matlab程序实现C均值聚类算法并作图显示的步骤:
1. 首先定义样本集合和聚类数量k
```matlab
X = [0.5,0.5; 1,0.5; 1,0; 1,1; 5,5; 6,5.5; 6,6; 7,0; 6,0.5; 7,-1; 8,-0.5];
k = 3; %聚类数量
```
2. 随机初始化聚类中心
```matlab
idx = randperm(size(X,1));
centroids = X(idx(1:k), :);
```
3. 不断迭代直到聚类中心不再改变或达到最大迭代次数
```matlab
max_iters = 10;
for i=1:max_iters
%计算每个样本到聚类中心的距离
distances = pdist2(X, centroids);
%将每个样本分配到最近的聚类中心
[min_distances, min_indices] = min(distances, [], 2);
%更新聚类中心
for j=1:k
centroids(j,:) = mean(X(min_indices==j,:));
end
%如果聚类中心不再改变,退出迭代
if isequal(old_centroids, centroids)
break;
end
old_centroids = centroids;
end
```
4. 绘制聚类结果图
```matlab
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k'];
figure;
hold on;
for i=1:k
plot(X(min_indices==i,1), X(min_indices==i,2), strcat(colors(i), 'o'));
plot(centroids(i,1), centroids(i,2), strcat(colors(i), 'x'), 'MarkerSize', 15, 'LineWidth', 3);
end
hold off;
```
5. 对于控制变量法,可以通过改变聚类数量k和初始聚类中心来获得不同的结果。例如,当k=4时,可以设置初始聚类中心为:
```matlab
centroids = [0.5,0.5; 1,0.5; 1,1; 7,0];
```
整个程序如下:
```matlab
X = [0.5,0.5; 1,0.5; 1,0; 1,1; 5,5; 6,5.5; 6,6; 7,0; 6,0.5; 7,-1; 8,-0.5];
k = 3; %聚类数量
%随机初始化聚类中心
idx = randperm(size(X,1));
centroids = X(idx(1:k), :);
%不断迭代直到聚类中心不再改变或达到最大迭代次数
max_iters = 10;
for i=1:max_iters
%计算每个样本到聚类中心的距离
distances = pdist2(X, centroids);
%将每个样本分配到最近的聚类中心
[min_distances, min_indices] = min(distances, [], 2);
%更新聚类中心
for j=1:k
centroids(j,:) = mean(X(min_indices==j,:));
end
%如果聚类中心不再改变,退出迭代
if isequal(old_centroids, centroids)
break;
end
old_centroids = centroids;
end
%绘制聚类结果图
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k'];
figure;
hold on;
for i=1:k
plot(X(min_indices==i,1), X(min_indices==i,2), strcat(colors(i), 'o'));
plot(centroids(i,1), centroids(i,2), strcat(colors(i), 'x'), 'MarkerSize', 15, 'LineWidth', 3);
end
hold off;
```
阅读全文