Python-cdist函数中数组维度的问题
我正在尝试为k-means找到正确的聚类数,并为此使用cdist函数 我能理解cdist的论点应该是相同的维度。我试着打印两个参数的大小,分别是(2542,39)和(1,39) 有人能告诉我哪里出了问题吗Python-cdist函数中数组维度的问题,python,scipy,cluster-analysis,k-means,euclidean-distance,Python,Scipy,Cluster Analysis,K Means,Euclidean Distance,我正在尝试为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(
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.
ValueError回溯(最近一次调用)
在()
12预测=模型预测(tfidf_矩阵)
13打印(型号群集\中心\形状)
--->14平均畸变。附加(和(np.min(cdist(tfidf_矩阵,model.cluster_中心,欧氏),轴=1))/
15 tfidf_矩阵形状[0])
16
cdist中的~\Downloads\Conda\envs\data science\lib\site packages\scipy\space\distance.py(XA、XB、metric、*args、**kwargs)
2588
2589如果len(s)!=2:
->2590 raise VALUE ERROR('XA必须是二维数组')
2591如果len(sB)!=2:
2592 raise VALUERROR('XB必须是二维数组')
ValueError:XA必须是二维数组。
这可能是一个类型问题
Tfidf可能不是cdist要求的密集矩阵。当然,在这里使用稀疏矩阵是有意义的
然而,cdist似乎不接受稀疏矩阵:您的代码使用
tfidf_matrix=np.random.randn(2542,39)
并导入sklearn.cluster.KMeans
。您在均值扭曲.append()中缺少,
@ScottWarchal哦,是的,随机np数组带有(2542,39)对我来说也很好。如果尺寸不是问题,你能建议出什么问题吗?