Kmeans:k-means 聚类
k-means 聚类的一种实现。
from mlxtend.cluster import Kmeans
概述
聚类属于无监督学习范畴,它是机器学习的一个子领域,在实际应用中我们无法获得真实标签。在聚类中,我们的目标是根据相似性(在 k-means 中是欧几里得距离)对样本进行分组。
k-means 算法可以总结如下
- 从样本点中随机选取 k 个质心作为初始聚类中心。
- 将每个样本分配到最近的质心。.
- 将质心移动到分配给该质心的样本中心。
- 重复步骤 2 和 3,直到聚类分配不再改变,或达到用户定义的容忍度或最大迭代次数。
参考文献
- MacQueen, J. B. (1967). Some Methods for classification and Analysis of Multivariate Observations. Proceedings of 5th Berkeley Symposium on Mathematical Statistics and Probability. University of California Press. pp. 281–297. MR 0214227. Zbl 0214.46201. Retrieved 2009-04-07.
示例 1 - 三个斑点
加载一些样本数据
import matplotlib.pyplot as plt
from mlxtend.data import three_blobs_data
X, y = three_blobs_data()
plt.scatter(X[:, 0], X[:, 1], c='white')
plt.show()
计算聚类质心
from mlxtend.cluster import Kmeans
km = Kmeans(k=3,
max_iter=50,
random_seed=1,
print_progress=3)
km.fit(X)
print('Iterations until convergence:', km.iterations_)
print('Final centroids:\n', km.centroids_)
Iteration: 2/50 | Elapsed: 00:00:00 | ETA: 00:00:00
Iterations until convergence: 2
Final centroids:
[[-1.5947298 2.92236966]
[ 2.06521743 0.96137409]
[ 0.9329651 4.35420713]]
可视化聚类成员关系
y_clust = km.predict(X)
plt.scatter(X[y_clust == 0, 0],
X[y_clust == 0, 1],
s=50,
c='lightgreen',
marker='s',
label='cluster 1')
plt.scatter(X[y_clust == 1,0],
X[y_clust == 1,1],
s=50,
c='orange',
marker='o',
label='cluster 2')
plt.scatter(X[y_clust == 2,0],
X[y_clust == 2,1],
s=50,
c='lightblue',
marker='v',
label='cluster 3')
plt.scatter(km.centroids_[:,0],
km.centroids_[:,1],
s=250,
marker='*',
c='red',
label='centroids')
plt.legend(loc='lower left',
scatterpoints=1)
plt.grid()
plt.show()
API
Kmeans(k, max_iter=10, convergence_tolerance=1e-05, random_seed=None, print_progress=0)
K-means 聚类类。
在 0.4.1dev 中添加
参数
-
k
: int聚类数
-
max_iter
: int (默认值: 10)聚类分配期间的迭代次数。当算法收敛时,聚类重新分配会自动停止。
-
convergence_tolerance
: float (默认值: 1e-05)使用给定的容忍度(一个小的正浮点数)比较当前质心与前一次迭代的质心,以确定算法是否提前收敛。
-
random_seed
: int (默认值: None)设置初始质心分配的随机状态。
-
print_progress
: int (默认值: 0)在拟合过程中将进度打印到标准错误。0:无输出 1:已用迭代次数 2:1 加上已用时间 3:2 加上估计完成时间
属性
-
centroids_
: 2d-array, shape={k, n_features}k 个聚类质心的特征值。
-
custers_
: dictionary聚类分配以 Python 字典形式存储;字典键表示聚类索引,值是分配给每个聚类的样本索引的 Python 列表。
-
iterations_
: int收敛前的迭代次数。
示例
有关使用示例,请参阅 https://mlxtend.cn/mlxtend/user_guide/classifier/Kmeans/
方法
fit(X, init_params=True)
从训练数据中学习模型。
参数
-
X
: {类数组, 稀疏矩阵}, shape = [n_samples, n_features]训练向量,其中 n_samples 是样本数,n_features 是特征数。
-
init_params
: bool (默认值: True)在拟合之前重新初始化模型参数。设置为 False 可继续使用先前模型拟合的权重进行训练。
返回值
self
: object
predict(X)
从 X 中预测目标值。
参数
-
X
: {类数组, 稀疏矩阵}, shape = [n_samples, n_features]训练向量,其中 n_samples 是样本数,n_features 是特征数。
返回值
-
target_values
: 类数组, shape = [n_samples]预测的目标值。