2017-08-22 14 views
1

スパース行列とその転置の内積をとってみようとしています。私はscipy.sparseライブラリを使用して、結果が正しくないことを確認しています。下記参照:Pythonのスパース行列乗算問題

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

は、なぜあなたは 'DTYPE = uint8'を使用していますか? – jeremycg

答えて

2
あなたは256の最大値を持つ uint8のあなたのデータ型を使用している、そしておそらくあなたがあふれている、ここであなたに16

を与える10000%256で終わるように見えます

はあるものの例です 起こっ:

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

が私のために働くためにnp.int64あなたDTYPEを変更する:

dtype = np.int64 
+0

Doh - もちろん。コードスニペットをスパース行列の定義方法にコピーし、データ型にはっきりと注意を払っていませんでした。速やかなご返信ありがとうございます!! – shadowprice