python - 每次训练的 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)
我如何才能始终获得相同的结果(就每个集群中的观察次数而言)?
先感谢您
解决方案
这是来自文档
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_means
从scikit.cluster
设置return_n_iter
到True
获取best_n_iter
,它对应于迭代次数以获得最佳结果。
这是一个例子:
centroids, best_iter = k_means(X, n_clusters=2, init='kmeans++', random_state=0, return_n_iter=True)
推荐阅读
- mysql - 带组的 SQL Rank 函数
- nativescript - 来自用户手机的自定义图库
- c++ - 为什么 c++ std 累积总是返回 0
- spring - 如何使用 Spring Boot 禁用默认 Spring 安全性?
- compression - 纹理压缩从 4096 到 512 不损失质量
- c++ - E0312, C2664 尝试将矢量对象作为函数参数传递时出错
- r - 从正态分布生成数字
- amazon-web-services - 如何从关闭的 AWS SES 账户中恢复?
- time-complexity - 如何计算算法的时间复杂度 O(n)?
- laravel - Ionic 4 & Laravel API - 在 http 请求上获得空响应