matlab实现K-means聚类

clear;
clc;
% 随机生成二维数据点
n_max = 10;
n = 0;
point_data = rand(2,100)*200;
% 绘制原始点的分布
 K = 3;
%  随机生成了K个中心点
center = rand(2,3)*200;
while n<n_max
% 计算距离,进行分类
    h1 = (center(:,1) - point_data).^2;
    h2 = (center(:,2) - point_data).^2;
    h3 = (center(:,3) - point_data).^2;
    sum_h(1,:) = sum(h1);
    sum_h(2,:) = sum(h2);
    sum_h(3,:) = sum(h3);
% 开始依据分类分类
% b返回的是最小值对应的中心
    point_1 = [];
    point_2 = [];
    point_3 = [];
    [a,b] = min(sum_h);
% 对数据进行分类,归入不同的类中
    for i = 1:100
        if b(i)==1
            point_1 = [point_1 point_data(:,i)];
        elseif b(i)==2
            point_2 = [point_2 point_data(:,i)];
        else
            point_3 = [point_3 point_data(:,i)];
        end
    end
% 显示一下这一次的分组结果
    figure;
    hold on,scatter(point_1(1,:),point_1(2,:),'+','r');
    hold on,scatter(point_2(1,:),point_2(2,:),'+','g');
    hold on,scatter(point_3(1,:),point_3(2,:),'+','b');
    hold on,scatter(center(1,:),center(2,:),'s');
% 计算新分组结果的中心
    new_center(:,1) = mean(point_1,2);
    new_center(:,2) = mean(point_2,2);
    new_center(:,3) = mean(point_3,2);
    n=n+1;
    if new_center == center
        disp('K-means求解完成');
        break;
    else
        center = new_center;
    end
end

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
上面五张图展示的是一次分类的过程变化,代码确实实现了这个聚类的功能,可惜就是我首先设置了聚类的种类为3

point_data = rand(2,100)*200;
center = rand(2,3)*200;

用来产生数据和数据中心

    h1 = (center(:,1) - point_data).^2;
    h2 = (center(:,2) - point_data).^2;
    h3 = (center(:,3) - point_data).^2;
    sum_h(1,:) = sum(h1);
    sum_h(2,:) = sum(h2);
    sum_h(3,:) = sum(h3)

计算数据点中的每个点与设置的中心之间的距离

    point_1 = [];
    point_2 = [];
    point_3 = [];
    [a,b] = min(sum_h);
% 对数据进行分类,归入不同的类中
    for i = 1:100
        if b(i)==1
            point_1 = [point_1 point_data(:,i)];
        elseif b(i)==2
            point_2 = [point_2 point_data(:,i)];
        else
            point_3 = [point_3 point_data(:,i)];
        end
    end
% 显示一下这一次的分组

依据计算的结果,对数据点进行归类

    new_center(:,1) = mean(point_1,2);
    new_center(:,2) = mean(point_2,2);
    new_center(:,3) = mean(point_3,2);

计算分类后的数据的中心,然后比较中心点是否发生变化,中心点不在变化,或者迭代的次数已经超过最大值,循环结束。

    if new_center == center
        disp('K-means求解完成');
        break;
    else
        center = new_center;
    end
end
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值