【Python】K-means聚类(获取每个簇中的样本)
1. K-means介绍
k均值聚类算法(k-means clustering algorithm)是一种迭代求解的聚类分析算法,其步骤是,预将数据分为K组,则随机选取K个对象作为初始的聚类中心,然后计算每个对象与各个种子聚类中心之间的距离,把每个对象分配给距离它最近的聚类中心。聚类中心以及分配给它们的对象就代表一个聚类。每分配一个样本,聚类的聚类中心会根据聚类中现有的对象被重新计算。这个过程将不断重复直到满足某个终止条件。终止条件可以是没有(或最小数目)对象被重新分配给不同的聚类,没有(或最小数目)聚类中心再发生变化,误差平方和局部最小。
1.1 API
from sklearn.cluster import KMeans
KMeans(n_clusters=8,init='k-means++',n_init=10,max_iter=300,tol=0.0001,precompute_distances='auto',verbose=0,random_state=None,copy_x=True,n_jobs=1,algorithm='auto')
# n_clusters: class的个数;
# max_inter: 每一个初始化值下,最大的iteration次数;
# n_init: 尝试用n_init个初始化值进行拟合;
# tol: within-cluster sum of square to declare convergence;
# init= ‘k-means++’:可使初始化的centroids相互远离;
2. 代码示例
import numpy as np
from sklearn.cluster import KMeans
def clustering(Z):
model = KMeans(3, n_init=10)
cluster_id = model.fit_predict(Z)
print('聚类结果:', cluster_id)
clusters = []
for i in range(3):
clusters.append([j for j, x in enumerate(cluster_id) if x == i])
print('每个簇中的样本:', clusters)
n = len(cluster_id)
R = np.zeros((n, n))
for i in range(3):
c = [[x] for x in clusters[i]]
R[c, clusters[i]] = 1
print('矩阵对应点为1,则代表两个点在一个簇:\n', R)
x = np.array([[1.0, 1.0, 1.0],
[2.0, 3.0, 2.0],
[3.0, 3.0, 2.0],
[1.0, 3.0, 5.0],
[2.0, 3.0, 6.0],
[2.0, 1.0, 2.0],
[2.0, 4.0, 2.0],
[6.0, 3.0, 2.0],
[2.0, 0.0, 1.0],
[8.0, 3.0, 2.0],
])
clustering(x)
3. 输出结果
聚类结果: [0 0 0 2 2 0 0 1 0 1]
每个簇中的样本: [[0, 1, 2, 5, 6, 8], [7, 9], [3, 4]]
矩阵对应点为1,则代表两个点在一个簇:
[[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[0. 0. 0. 1. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 1. 0. 0. 0. 0. 0.]
[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 1.]
[1. 1. 1. 0. 0. 1. 1. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 1.]]