In [1]:
from scipy import linalg
import numpy as np
In [2]:
A = np.array([[1, 2], [3, 4]])
In [3]:
# Matrix Multiplication
A.dot(A)
Out[3]:
In [4]:
# Matrix Norm
linalg.norm(A)
Out[4]:
In [5]:
# CHECK: Matrix Norm
np.sqrt(sum([x**2 for x in range(1, 5)]))
Out[5]:
In [8]:
# Calc determinant
# For 2x2 matrix is a*d - b*c
linalg.det(A)
Out[8]:
In [9]:
print(A)
In [10]:
# Calc Matrix Inverse
A_inv = linalg.inv(A)
In [11]:
print(A_inv)
In [12]:
# CHECK: Inverse X original = identity matrix
A_inv.dot(A)
Out[12]:
In [13]:
# Compute Eigenvalues
In [14]:
# Decomposes A into a
# diagonal matrix x and invertible matrix y such that y * x * y^-1
x, y = linalg.eig(A)
x0, x1 = x[0], x[1]
y0, y1 = y[:, 0], y[:, 1]
In [25]:
y
Out[25]:
In [26]:
# Verify normal equation #1
print(A.dot(y0))
In [27]:
print(x0 * y0)
In [28]:
# Verify normal equation #2
print(A.dot(y1))
In [29]:
print(x1 * y1)
In [30]:
# verify eigenvalue decomposition
y.dot(np.diag(x).dot(linalg.inv(y)))
Out[30]:
In [31]:
# Calc singular value decomposition
# Extension to eigenvalues for non-invertible or non-square matrices
# product of an orthogonal matrix * diagonal matrix * another orthogonal matrix
u, s, v = linalg.svd(A)
In [32]:
# U is symmetric & orthogonal
print(u)
print(u.dot(u.T))
In [18]:
# Sigma is a diagonal matrix (if A is invertible)
print(np.diag(s))
In [19]:
# V is symmetric
print(v)
# V is orthogonal
print(v.dot(v.T))
In [20]:
# CHECK: singular value decomposition recovers A
u.dot(np.diag(s).dot(v))
Out[20]:
In [ ]: