強大到沒有朋友的科學計算庫,不知道怎么介紹ta!
大牛張若愚出了厚本的《Python 科學計算》第二版
里面包羅萬象,就不做搬運工了,盡快開工pandas。
來一彈在NLP自然語言處理中用到的稀疏矩陣處理:
# coding: utf-8
# # 稀疏矩陣
# `Scipy` 提供了稀疏矩陣的支持(`scipy.sparse`)。
#
# 稀疏矩陣主要使用 位置 + 值 的方法來存儲矩陣的非零元素,根據存儲和使用方式的不同,有如下幾種類型的稀疏矩陣:
#
# 類型|描述
# ---|----
# `bsr_matrix(arg1[, shape, dtype, copy, blocksize])`| Block Sparse Row matrix
# `coo_matrix(arg1[, shape, dtype, copy])`| A sparse matrix in COOrdinate format.
# `csc_matrix(arg1[, shape, dtype, copy])`| Compressed Sparse Column matrix
# `csr_matrix(arg1[, shape, dtype, copy])`| Compressed Sparse Row matrix
# `dia_matrix(arg1[, shape, dtype, copy])`| Sparse matrix with DIAgonal storage
# `dok_matrix(arg1[, shape, dtype, copy])`| Dictionary Of Keys based sparse matrix.
# `lil_matrix(arg1[, shape, dtype, copy])`| Row-based linked list sparse matrix
#
# 在這些存儲格式中:
#
# - COO 格式在構建矩陣時比較高效
# - CSC 和 CSR 格式在乘法計算時比較高效
# ## 構建稀疏矩陣
# In[1]:
from scipy.sparse import *
import numpy as np
# 創建一個空的稀疏矩陣:
# In[2]:
coo_matrix((2,3))
# 也可以使用一個已有的矩陣或數組或列表中創建新矩陣:
# In[4]:
A = coo_matrix([[1,2,0],[0,0,3],[4,0,5]])
print(A)
# 不同格式的稀疏矩陣可以相互轉化:
# In[5]:
type(A)
# In[6]:
B = A.tocsr()
type(B)
# 可以轉化為普通矩陣:
# In[7]:
C = A.todense()
C
# 與向量的乘法:
# In[8]:
v = np.array([1,0,-1])
A.dot(v)
# 還可以傳入一個 `(data, (row, col))` 的元組來構建稀疏矩陣:
# In[9]:
I = np.array([0,3,1,0])
J = np.array([0,3,1,2])
V = np.array([4,5,7,9])
A = coo_matrix((V,(I,J)),shape=(4,4))
# In[11]:
print(A)
# COO 格式的稀疏矩陣在構建的時候只是簡單的將坐標和值加到后面,對于重復的坐標不進行處理:
# In[13]:
I = np.array([0,0,1,3,1,0,0])
J = np.array([0,2,1,3,1,0,0])
V = np.array([1,1,1,1,1,1,1])
B = coo_matrix((V,(I,J)),shape=(4,4))
print(B)
# 轉換成 CSR 格式會自動將相同坐標的值合并:
# In[15]:
C = B.tocsr()
print(C)
# ## 求解微分方程
# In[16]:
from scipy.sparse import lil_matrix
from scipy.sparse.linalg import spsolve
from numpy.linalg import solve, norm
from numpy.random import rand
# 構建 `1000 x 1000` 的稀疏矩陣:
# In[17]:
A = lil_matrix((1000, 1000))
A[0, :100] = rand(100)
A[1, 100:200] = A[0, :100]
A.setdiag(rand(1000))
# 轉化為 CSR 之后,用 `spsolve` 求解 $Ax=b$:
# In[18]:
A = A.tocsr()
b = rand(1000)
x = spsolve(A, b)
# 轉化成正常數組之后求解:
# In[19]:
x_ = solve(A.toarray(), b)
# 查看誤差:
# In[20]:
err = norm(x-x_)
err
# ## sparse.find 函數
# 返回一個三元組,表示稀疏矩陣中非零元素的 `(row, col, value)`:
# In[22]:
from scipy import sparse
row, col, val = sparse.find(C)
print(row, col, val)
# ## sparse.issparse 函數
# 查看一個對象是否為稀疏矩陣:
# In[23]:
sparse.issparse(B)
# 或者
# In[24]:
sparse.isspmatrix(B.todense())
# 還可以查詢是否為指定格式的稀疏矩陣:
# In[25]:
sparse.isspmatrix_coo(B)
# In[26]:
sparse.isspmatrix_csr(B)
膠水語言博大精深,
本主只得一二為新人帶路,
新手可查閱歷史目錄:yeayee:Python數據分析及可視化實例目錄?zhuanlan.zhihu.com
最后,別只收藏不關注哈