data=xlsread('D:\usedata\lastdata3.xlsx') data=data(:,1:2) % 设置参数 options = [2, 100, 1e-5, 0]; % 运行FCM聚类 [centers,U] = fcm(data, 4, options); % 可视化结果 figure;plot(data(:,1), data(:,2), 'o'); hold on; maxU = max(U); index1 = find(U(1,:) == maxU); index2 = find(U(2,:) == maxU); index3 = find(U(3,:) == maxU); index4 = find(U(4,:) == maxU); line(data(index1,1), data(index1,2), 'linestyle', 'none', 'marker', 'o', 'color', 'g'); line(data(index2,1), data(index2,2), 'linestyle', 'none', 'marker', 'o', 'color', 'r'); line(data(index3,1), data(index3,2), 'linestyle', 'none', 'marker', 'o', 'color', 'b'); line(data(index4,1), data(index4,2), 'linestyle', 'none', 'marker', 'o', 'color', 'c'); plot(centers(1,1), centers(1,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k'); plot(centers(2,1), centers(2,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k'); plot(centers(3,1), centers(3,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k'); plot(centers(4,1), centers(4,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k'); disp('聚类中心:') disp(centers) for i = 1:size(centers,1) disp(['第',num2str(i),'个聚类的范围:']) index = find(U(i,:) == maxU); range = [min(data(index,1)), max(data(index,1)), min(data(index,2)), max(data(index,2))]; disp(range) end在这个代码中让初始聚类中心为指定值
时间: 2023-06-27 18:01:26 浏览: 66
要让初始聚类中心为指定值,可以在运行FCM聚类之前,使用kmeans算法来得到初始聚类中心。具体步骤如下:
1. 使用kmeans算法得到初始聚类中心。假设你要将数据分为4类,可以这样写代码:
```
[idx, centers] = kmeans(data, 4);
```
其中,idx是每个样本所属的类别编号,centers是4个聚类中心的坐标。
2. 将得到的聚类中心作为参数传入FCM聚类函数,并设置其他参数。比如,可以这样写:
```
options = [2, 100, 1e-5, 0];
[~, U, ~, ~, centers] = fcm(data, 4, options, centers);
```
其中,第4个参数是指定初始聚类中心的位置,其他参数的含义可以参考FCM聚类函数的帮助文档。
3. 可视化聚类结果。与原来的代码类似,只需要用得到的聚类中心和U矩阵来绘制图形即可。
```
figure;
plot(data(:,1), data(:,2), 'o'); hold on;
maxU = max(U);
index1 = find(U(1,:) == maxU);
index2 = find(U(2,:) == maxU);
index3 = find(U(3,:) == maxU);
index4 = find(U(4,:) == maxU);
line(data(index1,1), data(index1,2), 'linestyle', 'none', 'marker', 'o', 'color', 'g');
line(data(index2,1), data(index2,2), 'linestyle', 'none', 'marker', 'o', 'color', 'r');
line(data(index3,1), data(index3,2), 'linestyle', 'none', 'marker', 'o', 'color', 'b');
line(data(index4,1), data(index4,2), 'linestyle', 'none', 'marker', 'o', 'color', 'c');
plot(centers(1,1), centers(1,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k');
plot(centers(2,1), centers(2,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k');
plot(centers(3,1), centers(3,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k');
plot(centers(4,1), centers(4,2), 'x', 'linewidth', 2, 'markersize', 8, 'color', 'k');
disp('聚类中心:')
disp(centers)
for i = 1:size(centers,1)
disp(['第',num2str(i),'个聚类的范围:'])
index = find(U(i,:) == maxU);
range = [min(data(index,1)), max(data(index,1)), min(data(index,2)), max(data(index,2))];
disp(range)
end
```