基本流程:
导入包
import matplotlib.pyplot as plt
import numpy as np
import pylab as mpl # import matplotlib as mpl
from sklearn.datasets import make_blobs
画图问题:
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
数据集的生成
n_samples = 1500 # 生成1500个数据集
random_state = 170 # 170这个是随机种子
X, y = make_blobs(n_samples=n_samples, random_state=random_state) # 生成数据集,包括1500个样本
ages = np.vstack((X[y == 0][:500], X[y == 1][:500], X[y == 2][:500])) # 将数据进行堆叠,shape为(1500, 2)
y = np.array(([0] * 500 + [1] * 500 + [2] * 500)) #生成0 1 2 各500个
定义聚类中心:
k = 3 # 超参数
随机种子
np.random.seed(26) #给numpy设置一个随机种子,保证每次都能产生相同的值
初始化:
centers = np.zeros([3, 2]) # 生成0矩阵
centers_random = np.random.choice(range(len(y)), 3) # 迭代起点
centers_new = ages[centers_random] # 随机选取中心
dis_to_cent = np.zeros((k, len(ages))) # 一个二维数据,相当于一个空的容器
进行聚类中心的判断:
while not (centers_new == centers).all():
centers = centers_new.copy() # 注意python的赋值过程,进行展开讲解,== is 和复制方式,这里是浅拷贝
for ii in range(k):
dis_to_cent[ii] = np.linalg.norm(ages - centers[ii], axis=1) # 计算每个数值到中心的距离
clusters = dis_to_cent.argmin(axis=0) # 划分出每个类别
for ii in range(k): # 重新计算中心
cluster = ages[clusters == ii]
centers_new[ii] = ages[clusters == ii].mean(0)
print(centers, centers_new)
print(centers_new)
print('centers_new==centers?', (centers_new == centers).all())
print()
最后实现可视化的展示:
**plt.figure(figsize=(8, 4)) #创建画布
ax = plt.subplot(121) # 几行,几列,第几个,先按行数
ax.scatter(ages[:, 0], ages[:, 1], c=y) # x, y, 颜色,系统有基本的选择机制,不用写得太细
ax.set_title('数据本身的标签')
ax = plt.subplot(122) # 几行,几列,第几个,先按行数
ax.scatter(ages[:, 0], ages[:, 1], c=clusters) # x, y, 颜色,系统有基本的选择机制,不用写得太细
ax.set_title('聚类的结果')**
可视化的结果: