gpt4 book ai didi

python - scipy.sparse 矩阵的点例程产生错误

转载 作者:太空狗 更新时间:2023-10-30 01:02:15 29 4
gpt4 key购买 nike

我有一个 CSR matrix :

>> print type(tfidf)
<class 'scipy.sparse.csr.csr_matrix'>

我想对 CSR matrix 的两行进行点积:

>> v1 = tfidf.getrow(1)
>> v2 = tfidf.getrow(2)
>> print type(v1)
<class 'scipy.sparse.csr.csr_matrix'>

v1v2也是CSR矩阵。所以我使用 dot 子例程:

>> print v1.dot(v2)

Traceback (most recent call last):
File "cosine.py", line 10, in <module>
print v1.dot(v2)
File "/usr/lib/python2.7/dist-packages/scipy/sparse/base.py", line 211, in dot
return self * other
File "/usr/lib/python2.7/dist-packages/scipy/sparse/base.py", line 246, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch

它们是同一个矩阵的行,所以它们的维度应该匹配:

>> print v1.shape
(1, 4507)
>> print v2.shape
(1, 4507)

为什么 dot 子例程不起作用?

谢谢。

最佳答案

要执行两个行向量的点积,您必须转置一个。要转置的那个取决于您要查找的结果。

import scipy as sp

a = sp.matrix([1, 2, 3])
b = sp.matrix([4, 5, 6])

In [13]: a.dot(b.transpose())
Out[13]: matrix([[32]])

对比

In [14]: a.transpose().dot(b)
Out[14]:
matrix([[ 4, 5, 6],
[ 8, 10, 12],
[12, 15, 18]])

关于python - scipy.sparse 矩阵的点例程产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com