简单来说,K-means算法是一种无监督算法,不需要事先对数据集打上标签,即ground-truth,也可以对数据集进行分类,并且可以指定类别数目 牧师-村民模型
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
def create_data():
X,y = datasets.make_blobs(n_samples=1000,n_features=2,centers=[[1,0],[5,4],[2,3],[10,8],[7,4]])
return X,y
def init_centers(data,k):
m, n =data.shape
# m 样本个数,n特征个数
center_ids = np.random.choice(m,k)
centers = data[center_ids]
return centers
def cal_dist(ptA,ptB):
return np.linalg.norm(ptA-ptB)
def kmeans_process(data,k):
centers = init_centers(data, k)
m, n = data.shape
keep_changing = True
pred_y = np.zeros((m,))
while keep_changing:
keep_changing = False
# 计算剩余样本所属类别
for i in range(m):
min_distance = np.inf
for center in range(k):
distance = cal_dist(data[i,:],centers[center,:])
if distancemin_distance: # 判断离哪个更近
min_distance = distance
idx = center # 类别换下
if pred_y[i] != idx: # 判断是否发生了改变
keep_changing = True
pred_y[i] = idx
# 更新类别中心点坐标
for center in range(k):
cluster_data = data[pred_y==center]
centers[center,:] = np.mean(cluster_data, axis=0) # 求相同类别数据点的质心点
print(centers)
return centers, pred_y
if __name__ == '__main__':
X, y = create_data()
centers , pred_y = kmeans_process(data=X, k=5)
plt.scatter(X[:,0], X[:,1], s=3, c=pred_y)
plt.scatter(centers[:,0], centers[:,1], s=10, c='k')
plt.show()
到此这篇关于Python实现K-means聚类算法并可视化生成动图步骤详解的文章就介绍到这了,更多相关Python可视化K-means聚类算法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!