Python scipy.sparse矩陣使用方法

來源:互聯網
上載者:User

標籤:doc   orm   類型   ast   repr   cin   其他   href   vector   

本文以csr_matrix為例來說明sparse矩陣的使用方法,其他類型的sparse矩陣可以參考https://docs.scipy.org/doc/scipy/reference/sparse.html

csr_matrix是Compressed Sparse Row matrix的縮寫組合,下面介紹其兩種初始化方法

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

  where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

csr_matrix((data, indices, indptr), [shape=(M, N)])

  is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are             stored in data[indptr[i]:indptr[i+1]]. If the shape parameter is not supplied, the matrix dimensions are inferred from the index arrays.

 

上述官方文檔給出了:疏鬆陣列的參數及其含義、疏鬆陣列的構造方式。闡述形式簡單明了,讀起來令人賞心悅目。

 

Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power

Advantages of the CSR format

  • efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
  • efficient row slicing
  • fast matrix vector products

Disadvantages of the CSR format

  • slow column slicing operations (consider CSC)
  • changes to the sparsity structure are expensive (consider LIL or DOK)

 

上述官方文檔時疏鬆陣列的一些特性以及csr_matrix的優缺點,並且在指明各種缺點的同時,提供了可以考慮的技術實現。

 

程式碼範例1

import numpy as npfrom scipy.sparse import csr_matrixrow = np.array([0, 0, 1, 2, 2, 2])col = np.array([0, 2, 2, 0, 1, 2])data = np.array([1, 2, 3, 4, 5, 6])a = csr_matrix((data, (row, col)), shape=(3, 3)).toarray()

print(a)

運行結果:

array([[1, 0, 2],       [0, 0, 3],       [4, 5, 6]])

程式碼範例2

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])a = csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()print(a)

允許結果:

array([[1, 0, 2],       [0, 0, 3],       [4, 5, 6]])

 

上述兩個程式碼範例也是摘自官方文檔,表明了每種初始化方式的簡單實現,給應用這種初始化方式的人很大啟發。

 

總結:官方文檔其實是很好的書寫程式文檔範例,欣賞她,模仿她,然後在實際中應用她...

Python scipy.sparse矩陣使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.