122 KiB
122 KiB
In [1]:
import numpy as np
X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
Xinv = np.linlag.pinv(X)[0;31m---------------------------------------------------------------------------[0m
[0;31mAttributeError[0m Traceback (most recent call last)
Input [0;32mIn [1][0m, in [0;36m<cell line: 3>[0;34m()[0m
[1;32m 1[0m [38;5;28;01mimport[39;00m [38;5;21;01mnumpy[39;00m [38;5;28;01mas[39;00m [38;5;21;01mnp[39;00m
[1;32m 2[0m X [38;5;241m=[39m np[38;5;241m.[39marray( [ [[38;5;241m1[39m,[38;5;241m2[39m,[38;5;241m3[39m],[[38;5;241m2[39m,[38;5;241m4[39m,[38;5;241m5[39m],[[38;5;241m3[39m,[38;5;241m5[39m,[38;5;241m6[39m]])
[0;32m----> 3[0m Xinv [38;5;241m=[39m [43mnp[49m[38;5;241;43m.[39;49m[43mlinlag[49m[38;5;241m.[39mpinv(X)
File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/__init__.py:315[0m, in [0;36m__getattr__[0;34m(attr)[0m
[1;32m 312[0m [38;5;28;01mfrom[39;00m [38;5;21;01m.[39;00m[38;5;21;01mtesting[39;00m [38;5;28;01mimport[39;00m Tester
[1;32m 313[0m [38;5;28;01mreturn[39;00m Tester
[0;32m--> 315[0m [38;5;28;01mraise[39;00m [38;5;167;01mAttributeError[39;00m([38;5;124m"[39m[38;5;124mmodule [39m[38;5;132;01m{!r}[39;00m[38;5;124m has no attribute [39m[38;5;124m"[39m
[1;32m 316[0m [38;5;124m"[39m[38;5;132;01m{!r}[39;00m[38;5;124m"[39m[38;5;241m.[39mformat([38;5;18m__name__[39m, attr))
[0;31mAttributeError[0m: module 'numpy' has no attribute 'linlag'In [2]:
import numpy as np
# SVD inversion
def SVDinv(A):
''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
SVD is numerically more stable than the inversion algorithms provided by
numpy and scipy.linalg at the cost of being slower.
'''
U, s, VT = np.linalg.svd(A)
print('test U')
print( (np.transpose(U) @ U - U @np.transpose(U)))
print('test VT')
print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
D = np.zeros((len(U),len(VT)))
D = np.diag(s)
UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
return np.matmul(V,np.matmul(invD,UT))
#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
# Non-singular square matrix
X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
print(X)
A = np.transpose(X) @ X
# Brute force inversion
B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)
C = SVDinv(A)
print(np.abs(B-C))In [3]:
import numpy as np
# SVD inversion
def SVDinv(A):
U, s, VT = np.linalg.svd(A)
# reciprocals of singular values of s
d = 1.0 / s
# create m x n D matrix
D = np.zeros(A.shape)
# populate D with n x n diagonal matrix
D[:A.shape[1], :A.shape[1]] = np.diag(d)
UT = np.transpose(U)
V = np.transpose(VT)
return np.matmul(V,np.matmul(D.T,UT))
A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
print(A)
# Brute force inversion of super-collinear matrix
B = np.linalg.pinv(A)
print(B)
# Compare our own algorithm with pinv
C = SVDinv(A)
print(np.abs(C-B))Warning:
Output truncated. This notebook contains too many cells to display efficiently.