2014-12-06 211 views
1

林试图解决一个聚类problem..I具有由CountVectorizer产生()功能。本TFIDF加权向量的列表的数据类型:numpy的矩阵尺寸-TFIDF矢量

<1000x5369 sparse matrix of type '<type 'numpy.float64'>' 
with 42110 stored elements in Compressed Sparse Row format> 

我具有下列尺寸的“质心”载体:

<1x5369 sparse matrix of type '<type 'numpy.float64'>' 
with 57 stored elements in Compressed Sparse Row format> 

当尝试测量所述质心的余弦相似性,并通过下面的行的代码在我tfidf_vec_list其他载体:

for centroid in centroids: 
sim_scores=[cosine_similarity(vector,centroid) for vector in tfidf_vec_list] 

其中所述相似性函数是:

def cosine_similarity(vector1,vector2): 
    score=1-scipy.spatial.distance.cosine(vector1,vector2) 
    return score 

我得到错误:

Traceback (most recent call last): 
    File "<pyshell#25>", line 1, in <module> 
    sim_scores=[cosine_similarity(vector,centroid) for vector in tfidf_vec_list] 
    File "/home/ashwin/Desktop/Python-2.7.9/programs/test_2.py", line 28, in    cosine_similarity 
    score=1-scipy.spatial.distance.cosine(vector1,vector2) 
    File "/usr/lib/python2.7/dist-packages/scipy/spatial/distance.py", line 287, in cosine 
    dist = 1.0 - np.dot(u, v)/(norm(u) * norm(v)) 
    File "/usr/lib/python2.7/dist-packages/scipy/sparse/base.py", line 302, in __mul__ 
    raise ValueError(**'dimension mismatch'**) 

我已经试过各种包括矩阵中的每个向量转换成一个阵列和一个list.But我得到同样的错误!

+0

看起来像矢量和质心有不同的尺寸,所以检查这两个向量长度 – 2014-12-06 22:45:25

+0

@ Michael Plakhov不 - 他们有相同的尺寸:1 * 5369这是我无法理解的 – 2014-12-06 23:49:49

+0

这种向量中的什么样的元素?我是指典型的大小? – 2014-12-07 09:38:20

回答

3

scipy.spatial.distance.cosine似乎不支持稀疏矩阵输入。具体而言,np.linalg.norm(sparse_vector)失败(请参阅Get norm of numpy sparse matrix rows)。

如果你路过它们之前都转换输入向量(实际上他们在这里以矩阵形式行向量),以密集的版本,它工作得很好:

>>> xs 
<1x4 sparse matrix of type '<class 'numpy.int64'>' 
     with 3 stored elements in Compressed Sparse Row format> 
>>> ys 
<1x4 sparse matrix of type '<class 'numpy.int64'>' 
     with 3 stored elements in Compressed Sparse Row format> 
>>> cosine(xs, ys) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python3.4/site-packages/scipy/spatial/distance.py", line 296, in cosine 
    dist = 1.0 - np.dot(u, v)/(norm(u) * norm(v)) 
    File "/usr/lib/python3.4/site-packages/scipy/sparse/base.py", line 308, in __mul__ 
    raise ValueError('dimension mismatch') 
ValueError: dimension mismatch 
>>> cosine(xs.todense(), ys.todense()) 
-2.2204460492503131e-16 

这应该是罚款,只有个别5369元矢量(而不是整个矩阵)。

+0

@ HapeMask ..我错过了这个问题。我做了同样的事情。当矩阵转换为稠密矩阵时,它工作得很好。在处理距离度量和稀疏矩阵时,需要注意一点。 – 2014-12-09 19:42:16