% 生成随机数据点
num_points = 150;
data = [randn(num_points, 2)+1.5; randn(num_points, 2)+4; randn(num_points, 2)+7];
% 设置聚类数量
k = 3;
% 随机选择K个数据点作为初始的聚类中心
idx = randsample(size(data, 1), k);
centroids = data(idx, :);
% 初始化变量
max_iters = 10;
num_points = size(data, 1);
idx = zeros(num_points, 1);
% 迭代更新聚类中心
for iter = 1:max_iters
% 分配每个点到最近的聚类中心
for i = 1:num_points
distances = zeros(k, 1);
for j = 1:k
distances(j) = norm(data(i, :) - centroids(j, :));
end
[~, cluster_idx] = min(distances);
idx(i) = cluster_idx;
end
% 更新聚类中心
for j = 1:k
centroids(j, :) = mean(data(idx == j, :));
end
end
% 绘制结果
colors = ['r', 'g', 'b'];
figure;
hold on;
for j = 1:k
cluster_points = data(idx == j, :);
scatter(cluster_points(:, 1), cluster_points(:, 2), 25, colors(j), 'filled');
scatter(centroids(j, 1), centroids(j, 2), 100, colors(j), 'filled', 'd');
end
hold off;
使用matlab语言实现k-means算法
最新推荐文章于 2024-05-17 23:29:48 发布