<<

Python For Data Science Cheat Sheet Linear Algebra Also see You’ll use the linalg and sparse modules. Note that scipy.linalg contains and expands on numpy.linalg. SciPy - Linear Algebra Matrix Functions Learn More Python for Data Science Interactively at www.datacamp.com >>> from scipy import linalg, sparse Creating Matrices Addition >>> np.add(A,D) Addition >>> A = np.matrix(np.random.random((2,2))) Subtraction >>> B = np.asmatrix(b) Subtraction SciPy >>> = np.mat(np.random.random((10,5))) >>> np.subtract(A,D) The SciPy library is one of the core packages for >>> D = np.mat([[3,4], [5,6]]) Division scientific computing that provides mathematical >>> np.divide(A,D) Division Basic Matrix Routines Multiplication algorithms and convenience functions built on the Inverse >>> A @ D Multiplication operator (Python 3) NumPy extension of Python. >>> A.I Inverse >>> np.multiply(D,A) Multiplication >>> linalg.inv(A) Inverse >>> np.dot(A,D) Dot product Interacting With NumPy Also see NumPy Transposition Vector dot product Tranpose matrix >>> np.vdot(A,D) >>> import numpy as np >>> A.T >>> np.inner(A,D) Inner product >>> A.H Conjugate transposition >>> a = np.array([1,2,3]) >>> np.outer(A,D) Outer product >>> b = np.array([(1+5j,2j,3j), (4j,5j,6j)]) Trace >>> np.tensordot(A,D) Tensor dot product >>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]]) >>> np.trace(A) Trace >>> np.kron(A,D) Kronecker product Norm Exponential Functions Index Tricks Matrix exponential >>> linalg.norm(A) Frobenius norm >>> linalg.expm(A) Create a dense meshgrid L1 norm (max column sum) >>> linalg.expm2(A) Matrix exponential (Taylor Series) >>> np.mgrid[0:5,0:5] >>> linalg.norm(A,1) Matrix exponential (eigenvalue >>> np.ogrid[0:2,0:2] Create an open meshgrid L inf norm (max row sum) >>> linalg.expm3(D) decomposition) Stack arrays vertically (row-wise) >>> linalg.norm(A,np.inf) >>> np.r_[3,[0]*5,-1:1:10j] Rank Logarithm Function >>> np.c_[b,c] Create stacked column-wise arrays >>> np.linalg.matrix_rank(C) Matrix rank >>> linalg.logm(A) Matrix logarithm Shape Manipulation Determinant Trigonometric Functions >>> linalg.det(A) Determinant >>> linalg.sinm(D) Matrix sine >>> np.transpose(b) Permute array dimensions Solving linear problems >>> linalg.cosm(D) Matrix cosine >>> b.flatten() Flatten the array >>> linalg.tanm(A) Matrix tangent Stack arrays horizontally (column-wise) >>> linalg.solve(A,b) Solver for dense matrices >>> np.hstack((b,c)) Solver for dense matrices Hyperbolic Trigonometric Functions >>> np.vstack((a,b)) Stack arrays vertically (row-wise) >>> E = np.mat(a).T Split the array horizontally at the 2nd index >>> linalg.lstsq(F,E) Least-squares solution to linear matrix >>> linalg.sinhm(D) Hypberbolic matrix sine >>> np.hsplit(c,2) equation Hyperbolic matrix cosine >>> np.vpslit(d,2) Split the array vertically at the 2nd index >>> linalg.coshm(D) Generalized inverse >>> linalg.tanhm(A) Hyperbolic matrix tangent Polynomials >>> linalg.pinv(C) Compute the pseudo-inverse of a matrix Matrix Sign Function (least-squares solver) >>> np.signm(A) Matrix sign function >>> from numpy import poly1d Create a polynomial object >>> linalg.pinv2(C) Compute the pseudo-inverse of a matrix Matrix Square Root >>> p = poly1d([3,4,5]) (SVD) >>> linalg.sqrtm(A) Matrix square root Vectorizing Functions Creating Sparse Matrices Arbitrary Functions Evaluate matrix function >>> def myfunc(a): >>> linalg.funm(A, lambda x: x*x) if a < 0: >>> F = np.eye(3, k=1) Create a 2X2 identity matrix return a*2 >>> G = np.mat(np.identity(2)) Create a 2x2 identity matrix Decompositions else: >>> C[C > 0.5] = 0 return a/2 Compressed Sparse Row matrix Eigenvalues and Eigenvectors Vectorize functions >>> H = sparse.csr_matrix(C) >>> np.vectorize(myfunc) Compressed Sparse Column matrix >>> la, v = linalg.eig(A) Solve ordinary or generalized >>> I = sparse.csc_matrix(D) eigenvalue problem for square matrix >>> J = sparse.dok_matrix(A) Dictionary Of Keys matrix Type Handling >>> E.todense() Sparse matrix to full matrix >>> l1, l2 = la Unpack eigenvalues >>> sparse.isspmatrix_csc(A) Identify sparse matrix >>> v[:,0] First eigenvector >>> np.real(b) Return the real part of the array elements Second eigenvector Return the imaginary part of the array elements >>> v[:,1] >>> np.imag(b) Sparse Matrix Routines >>> linalg.eigvals(A) Unpack eigenvalues >>> np.real_if_close(c,tol=1000) Return a real array if complex parts close to 0 Cast object to a data type Singular Value Decomposition >>> np.cast['f'](np.pi) Inverse Singular Value Decomposition (SVD) Inverse >>> U,s,Vh = linalg.svd(B) Other Useful Functions >>> sparse.linalg.inv(I) >>> M,N = B.shape Norm >>> Sig = linalg.diagsvd(s,M,N) Construct sigma matrix in SVD Return the angle of the complex argument Norm >>> np.angle(b,deg=True) >>> sparse.linalg.norm(I) LU Decomposition Create an array of evenly spaced values >>> g = np.linspace(0,np.pi,num=5) Solving linear problems >>> P,L,U = linalg.lu(C) LU Decomposition (number of samples) Solver for sparse matrices >>> g [3:] += np.pi >>> sparse.linalg.spsolve(H,I) >>> np.unwrap(g) Unwrap Sparse Matrix Decompositions >>> np.logspace(0,10,3) Create an array of evenly spaced values (log scale) Sparse Matrix Functions >>> np.select([c<4],[c*2]) Return values from a list of arrays depending on >>> la, v = sparse.linalg.eigs(F,1) Eigenvalues and eigenvectors SVD conditions >>> sparse.linalg.expm(I) Sparse matrix exponential >>> sparse.linalg.svds(H, 2) >>> misc.factorial(a) Factorial >>> misc.comb(10,3,exact=True) Combine N things taken at k time Asking For Help >>> misc.central_diff_weights(3) Weights for Np-point central derivative DataCamp >>> misc.derivative(myfunc,1.0) Find the n-th derivative of a function at a point >>> help(scipy.linalg.diagsvd) Learn Python for Data Science Interactively >>> np.info(np.matrix)