[참조]
공학자를 위한 Python, 조정래, 2022: 5. SciPy
https://wikidocs.net/15636
Dookie Kim, Python: From Beginning to Application, 2022
[PDF]
SciPy는 과학기술계산을 위한 라이브러리이다.
(1) sub 패키지
Clustering package (scipy.cluster)
Constants (scipy.constants)
Discrete Fourier transforms (scipy.fftpack)
Integration and ODEs (scipy.integrate)
Interpolation (scipy.interpolate)
Input and output (scipy.io)
Linear algebra (scipy.linalg)
Miscellaneous routines (scipy.misc)
Multi-dimensional image processing (scipy.ndimage)
Orthogonal distance regression (scipy.odr)
Optimization and root finding (scipy.optimize)
Signal processing (scipy.signal)
Sparse matrices (scipy.sparse)
Sparse linear algebra (scipy.sparse.linalg)
Compressed Sparse Graph Routines (scipy.sparse.csgraph)
Spatial algorithms and data structures (scipy.spatial)
Special functions (scipy.special)
Statistical functions (scipy.stats)
Statistical functions for masked arrays (scipy.stats.mstats)
Low-level callback functions
(2) 선형대수: linalg
1) 행렬 곱셈
Ex)
import numpy as np
import scipy.linalg as linalg
A = np.array([[1,2,-1],
[2,7,4],
[0,4,-1]])
X = np.array([1,0,1.2])
# A*X = Y: (3x3)*(3x1)=(3x1)
Y1 = np.matmul(A,X)
Y2 = np.dot(A,X)
Y3 = A.dot(X)
# A*X = Y: (3x3)*(3x4)=(3x4)
X = np.array([[1,2,3,4],
[-1,2,3,1],
[3,-2,5,9]])
Y1 = np.matmul(A,X)
Y2 = np.dot(A,X)
Y3 = A.dot(X)
2) determinant, solve, inverse
Ex-계속)
# 행렬식(determinant)
det = linalg.det(A)
# 솔버(solve)
Y = linalg.solve(A,X)
R = A.dot(Y) - B # 결과 검증 확인 = 0
# 역행렬(inverse)
Ainv = linalg.inv(A)
R = A@Ainv # 결과 검증 확인 = I
3) 노름(norm)
Ex-계속)
# 벡터 노름
norm1 = linalg.norm(X,1) # L1(ABS) norm == sum(np.abs(x))
norm2 = linalg.norm(X) # L2(SRSS) norm == np.sqrt(sum(x*x))
normMax = linalg.norm(X,np.inf) # max(최댓값) norm == np.max(abs(x))
4) 선형회귀(linear least square)
Ex)
import matplotlib.pyplot as plt
import numpy as np
from scipy import linalg
c1, c2 = 5.0, 2.0
X = np.linspace(0.1,1,100)
Y = c1*np.exp(-X) + c2*X
Z = Y + 0.05 * np.max(Y) * np.random.randn(len(Y))
A = np.vstack((np.exp(-X),X)).T # vertical 합치기
C,resid,rank,sigma = linalg.lstsq(A,Z)
X2 = np.linspace(0.1,1,100)
Y2 = C[0]*np.exp(-X2) + C[1]*X2
plt.plot(X,Z,'X',X2,Y2)
plt.axis([0,1.1,3.0,5.5])
plt.xlabel('$X