python - 为什么在 Google Colab 中重新启动运行时 KMeans 的 silhouette_score 会发生变化?

标签 python python-3.x scikit-learn google-colaboratory k-means

我试图从在 Google Colab 笔记本上运行的 sklearn 的 KMeans 获得可重现的结果。
Kmeans 算法正在拟合由主成分分析 (PCA) 生成的数组。
每次我重新启动笔记本的运行时,拟合、预测和生成 K-means 算法的剪影分数时,剪影分数都会发生变化!
这是我使用 Kmeans 进行拟合和预测并生成剪影分数的代码:

for n_clusters in range(3,9):
    kmeans = KMeans(init= 'k-means++', n_clusters = n_clusters, n_init= 25, random_state = 0)
    kmeans.fit(pca_mat_products)
    clusters = kmeans.predict(pca_mat_products)
    silhouette_avg = silhouette_score(mp_matrix, clusters, random_state= 0)
    print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg)
这是生成的剪影分数的示例:
For n_clusters = 3 The average silhouette_score is : 0.08689747798228342
For n_clusters = 4 The average silhouette_score is : 0.11513524544540599
For n_clusters = 5 The average silhouette_score is : 0.13225896257848024
For n_clusters = 6 The average silhouette_score is : 0.13390795741576195
For n_clusters = 7 The average silhouette_score is : 0.11262045164741093
For n_clusters = 8 The average silhouette_score is : 0.12179451798486395
当我重新启动笔记本的运行时,同时保持笔记本上的所有内容(包括 random_state = 0)相同,并从头开始运行单元格时,每次重新启动笔记本时都会出现新的剪影分数。
这是相同代码在不同运行中生成的剪影分数:
For n_clusters = 3 The average silhouette_score is : 0.09181951382862036
For n_clusters = 4 The average silhouette_score is : 0.11539863985647045
For n_clusters = 5 The average silhouette_score is : 0.13363229313208771
For n_clusters = 6 The average silhouette_score is : 0.13428788881085452
For n_clusters = 7 The average silhouette_score is : 0.13187306014661757
For n_clusters = 8 The average silhouette_score is : 0.13252806332855294
在进一步的运行时,silhouette_scores 不断变化。
mp_matrix 是一个单热编码数组,如下所示:
array([[0, 0, 0, ..., 0, 1, 0],
       [0, 0, 0, ..., 0, 1, 0],
       [0, 0, 0, ..., 0, 1, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [1, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]])
在 Google Colab 中重新启动运行时后,silhouette_scores 发生变化是否正常?
有没有办法获得可重复的剪影分数?
我已经在这里和在线其他地方搜索过,但没有发现正在讨论这个问题。
谢谢!
感谢您的帮助。

最佳答案

根据您的代码,您似乎正在根据 PCA 的结果进行聚类:

  kmeans.fit(pca_mat_products)
  clusters = kmeans.predict(pca_mat_products)
如果您需要 PCA 的可重现结果,也可以在那里设置 random_state。
这里的文档:https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

关于python - 为什么在 Google Colab 中重新启动运行时 KMeans 的 silhouette_score 会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67035336/

相关文章:

python - 如何理解字节对编码?

python - 来自 get_buy_price() 的 API Coinbase ValueError

elif循环中的python dict值

python - 有没有办法在 python 中的用户定义类上定义 list(obj) 方法?

python - 使用python从图像中删除CT床

python - 平均(似然)编码

python - Xgboost 适用于 pycharm,但不适用于 Jupyter NoteBook

python - 将数组中的十六进制转换为二进制

python - 如何在命令行中使用 http.server 作为参数传递 file.py?

python - Pyinstaller 和 sklearn.ensemble : 'ModuleNotFoundError: No module named ' sklearn.neighbors.quad_tree'[2760]'