Python的稀疏矩阵乘法问题

时间:2017-08-22 19:43:17

标签: python scipy sparse-matrix

我试图采用稀疏矩阵及其转置的点积。我正在使用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)

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您似乎正在使用uint8的数据类型,其最大值为256,并且可能是溢出的,最后是10000%256,这样会给你16个。

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

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

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

dtype = np.int64