首页 > 解决方案 > 每次训练的 Kmeans 聚类变化

问题描述

我正在使用 sklearn Kmeans 算法将多个观察结果分组为 4 个集群,并且我已经包含了 init_state 和 seed 以获得始终相同的结果;但是每次我在 google colab 中重新加载代码并且每次运行训练时,我都会在每个集群中的观察数量方面获得不同的结果,这里是代码:

 import numpy as np
 np.random.seed(5)
 from sklearn.cluster import KMeans
 kmeans = KMeans(n_clusters=4,init='k-means++',n_init=1,max_iter=3000,random_state=354)
 kmeans.fit(X)
 y_kmeans = kmeans.predict(X)

我如何才能始终获得相同的结果(就每个集群中的观察次数而言)?

先感谢您

标签: pythonscikit-learnk-means

解决方案


这是来自文档

If the algorithm stops before fully converging (because of ``tol`` or
``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,
i.e. the ``cluster_centers_`` will not be the means of the points in each
cluster. Also, the estimator will reassign ``labels_`` after the last
iteration to make ``labels_`` consistent with ``predict`` on the training
set.

要更好地处理max_iter,请参阅k_meansscikit.cluster设置return_n_iterTrue获取best_n_iter,它对应于迭代次数以获得最佳结果。

这是一个例子:

centroids, best_iter = k_means(X, n_clusters=2, init='kmeans++', random_state=0, return_n_iter=True)

推荐阅读