M进阶_Kmeans算法实现

这篇博客介绍了无监督聚类中的K均值算法,通过实例展示了算法的步骤:选择初始聚类中心,计算点到中心的距离并分配类别,更新中心坐标,不断迭代直到达到预设次数。代码使用Python实现,绘制了聚类过程的动态图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# coding:utf-8
# 当前的项目名:code
# 当前编辑文件名:kmeans_main
# 当前系统日期:2022/8/1 0001

说明

无监督聚类

定义:

事先选定好 K 个聚类中心(假设要分为 K 类)。
算出每一个点到这 K 个聚类中心的距离,然后把该点分配给距离它最近的一个聚类中心。
更新聚类中心。算出每一个类别里面所有点的平均值,作为新的聚类中心。
给定迭代此次数,不断重复步骤 2,3,达到该迭代次数后自动停止。

例子

import  numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['axes.unicode_minus']=False   #这两行需要手动设置

先定义簇数和迭代次数

num_cluster = 5 #簇数
step = 50 # 迭代次数
color = ["red", "blue", "grey", "yellow","orange"]  # 后续分类用

初始化值

x = np.random.random(500) * 10
y = np.random.random(500) * 10

center_x, center_y = [], []  # 中心坐标,平均值
res_x, res_y = [], []  # 每次迭代后每一小类的坐标

#随机500个点,在10以内.循环5次并画出来
for i in range(num_cluster):
    res_x.append([])
    res_y.append([])
    x1 = np.random.choice(x)
    y1 = np.random.choice(y)

    if x1 not in center_x and y1 not in center_y:
        center_x.append(x1)
        center_y.append(y1)

主函数

def main():
    """
kmeans 实现
:return:

for s in  range(step): # 迭代次数
    for i in range(len(x)): # 数据的长度
        dis =[] # 每个点到中心点的距离
        for j in range(len(center_x)):
            k = (center_x[j] -x[i]) **2 + (center_y[j]-y[i])**2
            # 欧式距离 x1 平方 +y1 平方  (x1-x2)**@ +(y1-y2)**2
            dis.append(k)
            dis.index(min(dis)) # 求距离最小的索引 [2,4,5].index(2) --> 0
            res_x[dis.index(min(dis))] # 0
            res_x[dis.index(min(dis))].append(x[i])
            res_y[dis.index(min(dis))].append(y[i])

        plt.title('iterations:'+str(s+1))

        for i in range(num_cluster):
            plt.scatter(res_x[i],res_y[i],c =color[i])
        # plt.show()

		# 暂停1S后关闭
        plt.show(block=False)
        plt.pause(1)
        plt.close()
        
        # 将位置更新
        center_x.clear()
        center_y.clear()
        for i in range(num_cluster):
            ave_x = np.mean(res_x[i])
            ave_y = np.mean(res_y[i])
            center_x.append(ave_x)
            center_y.append(ave_y)

 

if __name__ == '__main__':
    # init_plt() # 画图,可注释
    main()
    print(9**2)

原始画图

在这里插入图片描述

迭代

在这里插入图片描述

最后结果

在这里插入图片描述

补充

也可以新建一个列表或者字典去存储数据
将不同的分类数据存储到一块
如:
{“red”:[],“blue”:[],…}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值