【问题标题】:Sparse Matrix Multiplication Issue with PythonPython的稀疏矩阵乘法问题
【发布时间】:2017-08-23 03:59:29
【问题描述】:

我正在尝试获取稀疏矩阵的点积及其转置。我正在使用 scipy.sparse 库并发现结果不正确。见下文:

import numpy as np
import scipy.sparse 

#Define the dense matrix
matrix_dense = np.zeros([100000,10])
for i in range(10):
    i_0 = i*10000
    i_1 = (i+1)*10000
    matrix_dense[i_0:i_1,i] = 1

#Define the sparse matrix
cols = []
for i in range(10):
    cols+=[i]*10000

dtype = np.uint8 
rows = range(len(cols)) 
data_csc = np.ones(len(cols), dtype=dtype)
matrix_sparse = scipy.sparse.csc_matrix((data_csc, (rows, cols)), shape=(len(cols), 10), dtype=dtype)

#Check that the two matrices are identical
assert np.abs(matrix_sparse.todense() - matrix_dense).max() == 0 

#Dot product of the dense matrix
dense_product = np.dot(matrix_dense.T,matrix_dense)

#Dot product of the sparse matrix
sparse_product = (matrix_sparse.T)*(matrix_sparse)

正确答案(由dense_product给出)应该是一个对角矩阵,其中对角项等于10,000。

print dense_product
[[ 10000.      0.      0.      0.      0.      0.      0.      0.      0.
   0.]
 [     0.  10000.      0.      0.      0.      0.      0.      0.      0.
   0.]
 [     0.      0.  10000.      0.      0.      0.      0.      0.      0.
   0.]
 [     0.      0.      0.  10000.      0.      0.      0.      0.      0.
   0.]
 [     0.      0.      0.      0.  10000.      0.      0.      0.      0.
   0.]
 [     0.      0.      0.      0.      0.  10000.      0.      0.      0.
   0.]
 [     0.      0.      0.      0.      0.      0.  10000.      0.      0.
   0.]
 [     0.      0.      0.      0.      0.      0.      0.  10000.      0.
   0.]
 [     0.      0.      0.      0.      0.      0.      0.      0.  10000.
   0.]
 [     0.      0.      0.      0.      0.      0.      0.      0.      0.
   10000.]]

但是,无论我如何计算稀疏矩阵,结果都是不正确的:

print sparse_product.todense()
[[16  0  0  0  0  0  0  0  0  0]
 [ 0 16  0  0  0  0  0  0  0  0]
 [ 0  0 16  0  0  0  0  0  0  0]
 [ 0  0  0 16  0  0  0  0  0  0]
 [ 0  0  0  0 16  0  0  0  0  0]
 [ 0  0  0  0  0 16  0  0  0  0]
 [ 0  0  0  0  0  0 16  0  0  0]
 [ 0  0  0  0  0  0  0 16  0  0]
 [ 0  0  0  0  0  0  0  0 16  0]
 [ 0  0  0  0  0  0  0  0  0 16]]

我尝试了不同的方法来执行稀疏点积并得到完全相同的答案:

sparse_product_1 = np.dot(matrix_sparse.T,matrix_sparse)
sparse_product_2 = (matrix_sparse.T).dot(matrix_sparse)
sparse_product_3 = scipy.sparse.csr_matrix.dot((matrix_sparse.T), 
matrix_sparse)

知道发生了什么吗?

【问题讨论】:

  • 你为什么用dtype = uint8

标签: python scipy sparse-matrix


【解决方案1】:

您使用的数据类型似乎是 uint8,最大值为 256,并且您可能会溢出,最后是 10000%256,它给您 16。

下面是正在发生的事情的一个例子:

x = np.array(10000, dtype = np.uint8)
x
array(16, dtype=uint8)

将您的 dtype 更改为 np.int64 对我有用:

dtype = np.int64

【讨论】:

  • Doh - 当然。我复制了关于如何定义稀疏矩阵的代码sn-p,显然没有注意数据类型。感谢您的快速回复!
猜你喜欢
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多