matlab做k-means聚类详细代码
时间: 2023-08-24 20:08:07 浏览: 67
以下是Matlab实现k-means聚类的详细代码:
1. 加载数据
```matlab
data = load('data.txt');
```
2. 初始化聚类中心
```matlab
K = 3; % 聚类数
[m, n] = size(data); % 数据集大小
centroids = zeros(K, n); % 聚类中心
for i = 1:K
idx = randi(m); % 随机选择一个点作为聚类中心
centroids(i, :) = data(idx, :);
end
```
3. 迭代计算聚类中心
```matlab
max_iters = 10; % 最大迭代次数
for iter = 1:max_iters
% 计算每个点属于哪个聚类
idx = zeros(m, 1); % 初始化点的聚类
for i = 1:m
min_dist = inf; % 最小距离
for j = 1:K
dist = sum((data(i, :) - centroids(j, :)).^2); % 欧氏距离
if dist < min_dist
min_dist = dist;
idx(i) = j;
end
end
end
% 重新计算聚类中心
for j = 1:K
centroids(j, :) = mean(data(idx == j, :));
end
end
```
4. 可视化聚类结果
```matlab
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']; % 颜色
figure;
hold on;
for i = 1:K
plot(data(idx == i, 1), data(idx == i, 2), strcat('x', colors(i)));
plot(centroids(i, 1), centroids(i, 2), strcat('o', colors(i)), 'LineWidth', 2);
end
hold off;
```
完整代码如下:
```matlab
data = load('data.txt'); % 加载数据
K = 3; % 聚类数
[m, n] = size(data); % 数据集大小
centroids = zeros(K, n); % 聚类中心
for i = 1:K
idx = randi(m); % 随机选择一个点作为聚类中心
centroids(i, :) = data(idx, :);
end
max_iters = 10; % 最大迭代次数
for iter = 1:max_iters
% 计算每个点属于哪个聚类
idx = zeros(m, 1); % 初始化点的聚类
for i = 1:m
min_dist = inf; % 最小距离
for j = 1:K
dist = sum((data(i, :) - centroids(j, :)).^2); % 欧氏距离
if dist < min_dist
min_dist = dist;
idx(i) = j;
end
end
end
% 重新计算聚类中心
for j = 1:K
centroids(j, :) = mean(data(idx == j, :));
end
end
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']; % 颜色
figure;
hold on;
for i = 1:K
plot(data(idx == i, 1), data(idx == i, 2), strcat('x', colors(i)));
plot(centroids(i, 1), centroids(i, 2), strcat('o', colors(i)), 'LineWidth', 2);
end
hold off;
```
阅读全文