Python - cdist 函数中的数组维数问题

Python - Issue with the dimension of array in cdist function

我正在尝试为 k-means 找到正确的簇数,并为此使用 cdist 函数。

我可以理解 cdist 的参数应该是相同的维度。我尝试打印两个参数的大小,即 (2542, 39) 和 (1, 39)。

有人可以告诉我哪里出错了吗?

print(tfidf_matrix.shape) ### Returning --> (2542, 39)
#Finding optimal no. of clusters
from scipy.spatial.distance import cdist
clusters=range(1,10)
meanDistortions=[]

for k in clusters:
    model=KMeans(n_clusters=k)
    model.fit(tfidf_matrix)
    prediction=model.predict(tfidf_matrix)
    print(model.cluster_centers_.shape)  ## Returning (1, 39)
    meanDistortions.append(sum(np.min(cdist(tfidf_matrix, model.cluster_centers_, 'euclidean'), axis=1)) /
                           tfidf_matrix.shape[0])

错误:

ValueError                                Traceback (most recent call last)
<ipython-input-181-c15e32d863d2> in <module>()
     12     prediction=model.predict(tfidf_matrix)
     13     print(model.cluster_centers_.shape)
---> 14     meanDistortions.append(sum(np.min(cdist(tfidf_matrix, model.cluster_centers_, 'euclidean'), axis=1)) /
     15                            tfidf_matrix.shape[0])
     16 

~\Downloads\Conda\envs\data-science\lib\site-packages\scipy\spatial\distance.py in cdist(XA, XB, metric, *args, **kwargs)
   2588 
   2589     if len(s) != 2:
-> 2590         raise ValueError('XA must be a 2-dimensional array.')
   2591     if len(sB) != 2:
   2592         raise ValueError('XB must be a 2-dimensional array.')

ValueError: XA must be a 2-dimensional array.

可能是类型问题。

Tfidf 可能不是 cdist 要求的 dense 矩阵。当然这里使用稀疏矩阵是有意义的。

然而,cdist 似乎不接受稀疏矩阵: