0

我正在尝试使用 SOM 对我的数据进行聚类,首先我想获得最好的 K。但我需要一条线或其他东西来检测图中的最佳 K。我尝试使用 KElbowVisualizer() 但它总是显示错误:

YellowbrickTypeError:提供的模型不是聚类估计器;尝试使用分类器或回归分数可视化工具!

这是我的代码:

from sklearn_som.som import SOM
som = SOM(m = 1, n = i, dim = data.shape[1])
visualizer = KElbowVisualizer(som, k = (1,11))
visualizer.fit(data)
visualizer.show()

我还使用了 matplotlib 中的普通 Plot(),但我看不到 Best k,我的代码:

inertia = []
for i in range (1,31):
    som = SOM(m = 1, n = i, dim = data.shape[1])
    som.fit_predict(data)
    inertia.append(som.inertia_)
plt.plot(range(1,31), inertia)
plt.title('elbow method for SOM')
plt.xlabel('number of clusters')
plt.ylabel('WCSS')
plt.show()

这就是我从 Plot() 得到的情节

那么,请问我该如何在情节中或使用代码来做到这一点?

4

1 回答 1

1

我刚刚找到了我的问题的最佳解决方案。我决定把它贴在这里。可能是其他人需要它。

from kneed import KneeLocator

解决方案在这里只需将此库与 matplotlib 库一起使用

实现是这样的:

inertia = []
for i in range (1,31):
    som = SOM(m = 1, n = i, dim = x_lda_train.shape[1])
    som.fit_predict(x_lda_train)
    inertia.append(som.inertia_)
# identify the knee by using the kneelocator function
kneeloc1 = KneeLocator(range(1,11), wcss, curve='convex', direction='decreasing')
plt.plot(range(1,31), inertia)
plt.title('elbow method for SOM')
plt.xlabel('number of clusters')
plt.ylabel('WCSS')
# print it by using the vlines
plt.vlines(kneeloc1.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
plt.show()
# you can see this also as just a number by printing it
print(kneeloc1.knee)

有关更多信息,您可以查看文档:访问https://kneed.readthedocs.io/en/stable/parameters.html

于 2021-11-10T12:20:53.123 回答