1. 程式人生 > >scipy構建稀疏矩陣

scipy構建稀疏矩陣

數據 data imp sparse ces csr ipy 構建 numpy

from scipy.sparse import csr_matrix
import numpy as np
indptr  = np.array([0, 2, 3, 6])
indices = np.array([0, 2, 2, 0, 1, 2]) 
data    = np.array([1, 2, 3, 4, 5, 6]) #表示要構建稀疏矩陣的數據


#按照行來壓縮,
#方法:第i行(本例中i=0,1,2),
#非零數據列的索引為indices[indptr[i]:indptr[i+1]] 
#非零數據列的數據為   data[indptr[i]:indptr[i+1]]
csr_matrix((data, indices, indptr),shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
from scipy.sparse import csc_matrix
#按照列來壓縮,
#方法:第i列(本例中i=0,1,2),
#非零數據行的索引為indices[indptr[i]:indptr[i+1]] 
#非零數據行的數據為   data[indptr[i]:indptr[i+1]]

csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
#和上面的例子正好是轉置
array([[1, 0, 4],
       [0, 0, 5],
       [2, 3, 6]])

scipy構建稀疏矩陣