Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

python - Access value, column index, and row_ptr data from scipy CSR sparse matrix

I have a large matrix that I would like to convert to sparse CSR format.

When I do:

import scipy as sp
Ks = sp.sparse.csr_matrix(A)

print Ks

Where A is dense, I get

 (0, 0) -2116689024.0
 (0, 1) 394620032.0
 (0, 2) -588142656.0
 (0, 12)    1567432448.0
 (0, 14)    -36273164.0
 (0, 24)    233332608.0
 (0, 25)    23677192.0
 (0, 26)    -315783392.0
 (0, 45)    157961968.0
 (0, 46)    173632816.0

etc...

I can get vectors of row index, column index, and value using:

Knz = Ks.nonzero()
sparserows = Knz[0]
sparsecols = Knz[1]

#The Non-Zero Value of K at each (Row,Col) 
vals = np.empty(sparserows.shape).astype(np.float)
for i in range(len(sparserows)):

    vals[i] = K[sparserows[i],sparsecols[i]]

But is it possible to extract the vectors supposedly contained in the sparse CSR format (Value, Column Index, Row Pointer)?

SciPy's documentation explains that a CSR matrix could be generated from those three vectors, but I would like to do the opposite, get those three vectors out.

What am I missing?

Thanks for the time!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
value = Ks.data
column_index = Ks.indices
row_pointers = Ks.indptr

I believe these attributes are undocumented which may make them subject to change, but I've used them on several versions of scipy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...