【问题标题】:Numpy matrix dimensions-tfidf vectorNumpy 矩阵维度-tfidf 向量
【发布时间】:2014-12-06 22:38:01
【问题描述】:

我正在尝试解决聚类问题。我有一个由 CountVectorizer() 函数生成的 tf-idf 加权向量列表。这是数据类型:

<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'**)

我已经尝试了所有方法,包括将矩阵转换为数组并将每个向量转换为列表。但是我得到了同样的错误!!

【问题讨论】:

  • 看起来向量和质心有不同的维度,所以检查这两个向量的长度
  • @Michael Plakhov Nope-它们具有相同的尺寸:1*5369,这是我无法理解的
  • 这个向量中有什么样的元素?我的意思是典型尺寸?
  • @Michael Plakhov..“Todense”工作...!

标签: python numpy vector tf-idf


【解决方案1】:

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 元素向量(而不是整个矩阵)。

【讨论】:

  • @HapeMask ..我忘记了这个问题。我做了同样的事情。当矩阵转换为密集矩阵时它工作正常......!在使用时要注意一个有趣的点距离度量和稀疏矩阵。
猜你喜欢
  • 2011-07-25
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 2013-03-22
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
相关资源
最近更新 更多