稀疏矩阵之间的余弦距离
Cosine distance between sparse matrices
我正在尝试了解如何使用 csr_matrix
API 及其 cosine
功能,我 运行 进入 dimension mismatch
问题。
我有以下两个 (3,3) 矩阵:
a = scipy.sparse.csr_matrix(np.reshape(np.arange(9), (3,3)))
b = scipy.sparse.csr_matrix(np.reshape(np.arange(9)*2+5, (3,3)))
我想计算 a[0]
和 b[0]
a-la cosine(a[0], b[0])
的余弦相似度(或余弦距离)。
如果我打印出 a[0], b[0]
的尺寸,我得到:
(<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>)
所以他们的尺寸匹配。但是尝试 cosine(a[0], b[0])
结果是 ValueError: dimension mismatch
。有什么想法吗?
所以问题是 numpy.dot() 不知道稀疏矩阵,在这里:http://docs.scipy.org/doc/scipy/reference/sparse.html
当我运行
>>> scipy.spatial.distance.cosine(a[0], b[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/scipy/spatial/distance.py", line 303, in cosine
return (1.0 - (np.dot(u, v.T) / \
File "/usr/lib64/python2.6/site-packages/scipy/sparse/base.py", line 287, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch
错误在 np.dot() 中,它不理解作为参数传递的 csr_matrix 对象。这可以通过以下方式解决:
>>> scipy.spatial.distance.cosine(a[0].toarray(), b[0].toarray())
array([[ 0.10197349]])
显然不是您正在寻找的答案,通过转换为密集数组您会失去性能优势,但至少这是导致您出现问题的原因。
我正在尝试了解如何使用 csr_matrix
API 及其 cosine
功能,我 运行 进入 dimension mismatch
问题。
我有以下两个 (3,3) 矩阵:
a = scipy.sparse.csr_matrix(np.reshape(np.arange(9), (3,3)))
b = scipy.sparse.csr_matrix(np.reshape(np.arange(9)*2+5, (3,3)))
我想计算 a[0]
和 b[0]
a-la cosine(a[0], b[0])
的余弦相似度(或余弦距离)。
如果我打印出 a[0], b[0]
的尺寸,我得到:
(<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>)
所以他们的尺寸匹配。但是尝试 cosine(a[0], b[0])
结果是 ValueError: dimension mismatch
。有什么想法吗?
所以问题是 numpy.dot() 不知道稀疏矩阵,在这里:http://docs.scipy.org/doc/scipy/reference/sparse.html
当我运行
>>> scipy.spatial.distance.cosine(a[0], b[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/scipy/spatial/distance.py", line 303, in cosine
return (1.0 - (np.dot(u, v.T) / \
File "/usr/lib64/python2.6/site-packages/scipy/sparse/base.py", line 287, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch
错误在 np.dot() 中,它不理解作为参数传递的 csr_matrix 对象。这可以通过以下方式解决:
>>> scipy.spatial.distance.cosine(a[0].toarray(), b[0].toarray())
array([[ 0.10197349]])
显然不是您正在寻找的答案,通过转换为密集数组您会失去性能优势,但至少这是导致您出现问题的原因。