【发布时间】: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