K-means算法聚类分析的MATLAB代码
时间: 2023-12-18 22:21:35 浏览: 78
以下是K-means算法聚类分析的MATLAB代码示例:
```matlab
% 生成待聚类数据
X = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% 初始聚类中心
initial_centroids = [X(1,:); X(2,:)];
% 运行K-means算法
K = size(initial_centroids, 1);
max_iters = 10;
[centroids, idx] = runkMeans(X, initial_centroids, max_iters);
% 可视化聚类结果
figure;
plotDataPoints(X, idx, K);
title('K-means Clustering');
% K-means算法实现
function [centroids, idx] = runkMeans(X, initial_centroids, max_iters)
% 初始化变量
[m, n] = size(X);
K = size(initial_centroids, 1);
centroids = initial_centroids;
previous_centroids = centroids;
idx = zeros(m, 1);
% 迭代更新聚类中心
for i=1:max_iters
fprintf('K-means iteration %d/%d...\n', i, max_iters);
idx = findClosestCentroids(X, centroids);
centroids = computeCentroids(X, idx, K);
if isequal(previous_centroids, centroids)
break;
end
previous_centroids = centroids;
end
end
% 计算每个样本点距离哪个聚类中心最近
function idx = findClosestCentroids(X, centroids)
K = size(centroids, 1);
idx = zeros(size(X,1), 1);
for i=1:size(X,1)
distances = sum((X(i,:) - centroids).^2, 2);
[min_distance, idx(i)] = min(distances);
end
end
% 计算每个聚类的新中心
function centroids = computeCentroids(X, idx, K)
[m n] = size(X);
centroids = zeros(K, n);
for i=1:K
indices = find(idx == i);
centroids(i,:) = mean(X(indices,:));
end
end
% 绘制聚类结果
function plotDataPoints(X, idx, K)
colors = hsv(K);
for i=1:K
plot(X(idx==i,1), X(idx==i,2), '.', 'color', colors(i,:));
hold on;
end
end
```
该代码生成一个随机的二维数据集,并使用K-means算法将其分为两个簇。聚类结果可视化如下图所示:
![K-means聚类结果](https://img-blog.csdn.net/20180412161829309?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Rlc3QxOTk5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/70)
阅读全文