# 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”:[],…}