Kmeans 用matlab写代码
时间: 2023-12-03 22:46:21 浏览: 93
以下是Kmeans的Matlab代码示例:
```matlab
% 生成测试数据
data = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% 设定聚类数量
k = 2;
% 设定迭代次数
max_iters = 100;
% 随机初始化聚类中心
initial_centroids = kMeansInitCentroids(data, k);
% 运行 K-Means 算法
[centroids, idx] = runkMeans(data, initial_centroids, max_iters);
% 可视化聚类结果
plotKMeansData(data, idx, centroids, k);
```
其中 `kMeansInitCentroids` 和 `runkMeans` 是Kmeans算法的主要代码,下面给出这两个函数的代码实现:
```matlab
% 随机初始化聚类中心
function centroids = kMeansInitCentroids(X, K)
centroids = zeros(K, size(X, 2));
randidx = randperm(size(X, 1));
centroids = X(randidx(1:K), :);
end
% 运行 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(centroids, previous_centroids)
fprintf('K-Means algorithm converged after %d iterations.\n', i);
break;
end
previous_centroids = centroids;
end
end
% 计算每个样本点离哪个聚类中心最近
function idx = findClosestCentroids(X, centroids)
K = size(centroids, 1);
idx = zeros(size(X,1), 1);
m = size(X,1);
for i=1:m
min_dist = Inf;
for j=1:K
dist = sum((X(i,:) - centroids(j,:)).^2);
if dist < min_dist
idx(i) = j;
min_dist = dist;
end
end
end
end
% 更新聚类中心
function centroids = computeCentroids(X, idx, K)
[m, n] = size(X);
centroids = zeros(K, n);
for i=1:K
indices = find(idx == i);
Ck = length(indices);
centroids(i, :) = (1/Ck) * sum(X(indices,:));
end
end
```
最后,还需要一个函数来可视化聚类结果:
```matlab
% 可视化聚类结果
function plotKMeansData(X, idx, centroids, K)
colors = hsv(K);
figure;
hold on;
for i=1:K
data_points = X(idx==i,:);
scatter(data_points(:,1), data_points(:,2), 10, colors(i,:), 'filled');
end
scatter(centroids(:,1), centroids(:,2), 100, colors, 'x', 'LineWidth', 3);
hold off;
end
```
以上就是Kmeans在Matlab中的实现示例。
阅读全文