天天看點

#淺析# 使用Python中的scipy.sparse構造稀疏矩陣1. 簡介2. scipy.sparse的稀疏矩陣類型3. 矩陣初始化4. scipy.sparse中的矩陣函數

目錄

  • 1. 簡介
  • 2. scipy.sparse的稀疏矩陣類型
    • 2.1 bsr_matrix
    • 2.2 coo_matrix
    • 2.3 csc_matrix
    • 2.4 csr_matrix
    • 2.5 dia_matrix
    • 2.6 dok_matrix
    • 2.7 lil_matrix
    • 2.8 spmatrixSparse(基類型)
  • 3. 矩陣初始化
  • 4. scipy.sparse中的矩陣函數
    • 4.1 構造函數
    • 4.2 判别函數
    • 4.4 針對元素的函數
    • 4.5 轉化函數
    • 4.6 其他函數

1. 簡介

Python中的

scipy.sparse

,顧名思義就是一個用于初始化和操作稀疏矩陣的包,在

scipy.sparse

中的定義了8種稀疏矩陣結構,以下對sparse的常用功能做一些介紹,全面的介紹請參考官方網站

->https://docs.scipy.org/doc/scipy/reference/sparse.html。

2. scipy.sparse的稀疏矩陣類型

2.1 bsr_matrix

bsr_matrix(arg1[, shape, dtype, copy, blocksize])

Block Sparse Row matrix

>>> '''BSR矩陣中的inptr清單的第i個元素與i+1個元素是儲存第i行的資料的列索引以及資料的區間索引,即indices[indptr[i]:indptr[i+1]]為第i行元素的列索引,data[indptr[i]: indptr[i+1]]為第i行元素的data。
在下面的例子中,對于第0行,indptr[0]:indptr[1] -> 0:2, 是以第0行的列為indice[0:2]=[0,2],data為data[0:2]=array([[[1, 1],[1, 1]],[[2, 2],[2, 2]]]),對應的就是最後結果的第0,1行。'''
>>> 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]).repeat(4).reshape(6, 2, 2)
>>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
array([[1, 1, 0, 0, 2, 2],
       [1, 1, 0, 0, 2, 2],
       [0, 0, 0, 0, 3, 3],
       [0, 0, 0, 0, 3, 3],
       [4, 4, 5, 5, 6, 6],
       [4, 4, 5, 5, 6, 6]])
           

2.2 coo_matrix

coo_matrix(arg1[, shape, dtype, copy])

A sparse matrix in COOrdinate format:

>>> '''
不難發現,coo_matrix是可以根據行和列索引進行data值的累加。
'''
>>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
>>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
>>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[3, 0, 1, 0],
       [0, 2, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 1]])
           

2.3 csc_matrix

csc_matrix(arg1[, shape, dtype, copy])

Compressed Sparse Column matrix

csc_matrix的初始化方法可以是bsr_matrix的初始化方法,也可以是coo_matrix的初始化方法,該csc_matrix與下面的csr_matrix是比較常用的稀疏矩陣。

2.4 csr_matrix

csr_matrix(arg1[, shape, dtype, copy])

Compressed Sparse Row matrix

csr_matrix的初始化與csc_matrix一緻。

2.5 dia_matrix

dia_matrix(arg1[, shape, dtype, copy])

Sparse matrix with DIAgonal storage

>>> #data定義對角線元素,在這裡是[1,2,3,4]。
>>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
>>> #offsets定義對角線的偏移量,0代表正對角線,正數代表往上偏移,負數代表往下偏移
>>> offsets = np.array([0, -1, 2])
>>> dia_matrix((data, offsets), shape=(4, 4)).toarray()
array([[1, 0, 3, 0],
       [1, 2, 0, 4],
       [0, 2, 3, 0],
       [0, 0, 3, 4]])
           

2.6 dok_matrix

dok_matrix(arg1[, shape, dtype, copy])

Dictionary Of Keys based sparse matrix

dok_matrix可以高效地逐漸構造稀疏矩陣。

>>> S = dok_matrix((5, 5), dtype=np.float32)
>>> for i in range(5):
...     for j in range(5):
...         S[i, j] = i + j
>>> S.toarray()
array([[0., 1., 2., 3., 4.],
       [1., 2., 3., 4., 5.],
       [2., 3., 4., 5., 6.],
       [3., 4., 5., 6., 7.],
       [4., 5., 6., 7., 8.]], dtype=float32)
           

2.7 lil_matrix

lil_matrix(arg1[, shape, dtype, copy])

Row-based linked list sparse matrix

與dok_matrix類似,也是可以高效地插入元素更新矩陣。

2.8 spmatrixSparse(基類型)

spmatrixSparse([maxprint])

spmatrixSparse是上面所有稀疏矩陣類型的基類型,不能被執行個體化

3. 矩陣初始化

注意除最後一個基矩陣spmatrixSparse以外,其他七種稀疏矩陣都可以用以下方式來初始化,我們稀疏矩陣類型函數模闆化為sparse_matrix。

1、指定行索引、列索引以及對應的資料

2、指定array

3、稀疏矩陣之間的轉化

代碼如下:

>>> #行索引
>>> row  = np.array([0, 3, 1, 0])
>>> #列索引
>>> col  = np.array([0, 3, 1, 2])
>>> #具體資料
>>> data = np.array([4, 5, 7, 9])
>>> #第一種方式
>>> sparse_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[4, 0, 9, 0],
       [0, 7, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 5]])
>>> #第二種方式(array可以是list,也可以是np.array)
>>> sparse_matrix(array).toarray()
>>> #第三種方式(sparse_matrix_other為其他稀疏矩陣類型,等價于sparse_matrix_other.tosparse(),具體的内函數形式根據需要轉化的sparse_matrix類型而定)
>>> sparse_matrix(sparse_matrix_other).toarray()
           

4. scipy.sparse中的矩陣函數

下面我隻列出比較有用的函數,其他的函數可以參見scipy.sparse官網。

4.1 構造函數

  • eye(m[, n, k, dtype, format]):對角線為1的稀疏矩陣
  • identity(n[, dtype, format]):機關矩陣
  • diags(diagonals[, offsets, shape, format, dtype]):構造對角矩陣(含偏移量)
  • spdiags(data, diags, m, n[, format]):從矩陣中傳回含偏移量的對角稀疏矩陣
  • hstack(blocks[, format, dtype]) Stack sparse matrices horizontally (column wise)
  • vstack(blocks[, format, dtype]) Stack sparse matrices vertically (row wise)

4.2 判别函數

  • issparse(x):x是否為sparse類型
  • isspmatrix(x):x是否為sparse類型
  • isspmatrix_csc(x):x是否為csc_matrix類型
  • isspmatrix_csr(x):x是否為csr_matrix類型
  • isspmatrix_bsr(x):x是否為bsr_matrix類型
  • isspmatrix_lil(x):x是否為lil_matrix類型
  • isspmatrix_dok(x):x是否為dok_matrix類型
  • isspmatrix_coo(x):x是否為coo_matrix類型
  • isspmatrix_dia(x):x是否為dia_matrix類型

4.4 針對元素的函數

内函數中有很多作用在矩陣元素的函數,下面列出一些函數。

  • arcsin():每個元素進行arcsin運算
  • floor():每個元素進行floor運算
  • sqrt():每個元素進行sqrt運算
  • maximum(other):比較稀疏矩陣與other矩陣的每個元素,傳回最大值

4.5 轉化函數

  • todense([order, out]):傳回稀疏矩陣的np.matrix形式
  • toarray([order, out]):傳回稀疏矩陣的np.array形式
  • tobsr([blocksize, copy]):傳回稀疏矩陣的bsr_matrix形式
  • tocoo([copy]):傳回稀疏矩陣的coo_matrix形式
  • tocsc([copy]):傳回稀疏矩陣的csc_matrix形式
  • tocsr([copy]):傳回稀疏矩陣的csr_matrix形式
  • todia([copy]):傳回稀疏矩陣的dia_matrix形式
  • todok([copy]):傳回稀疏矩陣的dok_matrix形式
  • tolil([copy]):傳回稀疏矩陣的lil_matrix形式

4.6 其他函數

  • save_npz(file, matrix[, compressed]):以.npz格式儲存稀疏矩陣
  • load_npz(file):導入.npz格式的稀疏矩陣
  • find(A):傳回稀疏矩陣A中的非零元的位置以及數值
  • get_shape():傳回稀疏矩陣的次元
  • max([axis, out]):傳回稀疏矩陣沿着某個軸的最大值
  • reshape(self, shape[, order, copy]):将稀疏矩陣的次元重構
  • diagonal([k]):傳回第k個對角元素,但是在我的python3版本中k不起作用。
  • dot(other):與other矩陣的矩陣乘法