day2-ML code practice - part1: Linear Algebra-9.22
tasks for today:
1. matrix times matrix
2. mean vector
3. transformation from bases B to C
4. Singular Value Decomposition (SVD) [principle pending]
5. calculate matrix inverse
6. matrix transformation
-------------------------------------------------------
1.matrix times matrix
Refer to day1 for details in both numpy and pytorch.
def matrixmul(a:list[list[int|float]],
b:list[list[int|float]])-> list[list[int|float]]:
import numpy as np
A = np.array(a)
B = np.array(b)
if A.shape[1] == B.shape[0]:
c = np.dot(A, B).tolist()
return c
else:
return -1
2. mean vector
def calculate_matrix_mean(matrix: list[list[float]], mode: str) -> list[float]:
import numpy as np
Matrix = np.array(matrix)
if mode == 'column':
means = Matrix.mean(0)
else:
means = Matrix.mean(1)
return means
3. transformation form bases B to C
C*P=B => P = C^(-1)*B
def transform_basis(B: list[list[int]], C: list[list[int]]) -> list[list[float]]:
import numpy as np
B = np.array(B)
C = np.array(C)
P = np.linalg.inv(C).dot(B).tolist()
return P
4. SVD
import numpy as np
def svd(A):
AAT = np.dot(A, A.T)
ATA = np.dot(A.T, A)
eigen_valU, U = np.linalg.eig(AAT)
eigen_valV, V = np.linalg.eig(ATA)
sing_val = np.sqrt(np.abs(eigen_valU))
sort_idx = np.argsort(-sing_val)
sing_val_sort = sing_val[sort_idx]
U = U[:, sort_idx]
V = V[:, sort_idx]
return U, sing_val_sort, V.T
def svd_2x2_singular_values(A: np.ndarray) -> tuple:
# method 1: use in-built numpy function
#U, S, VT = np.linalg.svd(A, full_matrices=False)
# method 2: manually compose (SVD, eigenvalue)
SVD = svd(A)
return SVD
5. calculate matrix inverse
def inverse_2x2(matrix: list[list[float]]) -> list[list[float]]:
# method 1: with in-built library function
import numpy as np
try:
inverse = np.linalg.inv(np.array(matrix)).tolist()
return inverse
except:
return None
# method 2: manually for 2*2 matrix
a, b, c, d = matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1]
determinant = a*d - b*c
if determinant == 0:
return None
inverse = [[d/determinant, -b/determinant], [-c/determinant, a/determinant]]
return inverse
6.matrix transformation
import numpy as np
def transform_matrix(A: list[list[int|float]], T: list[list[int|float]], S: list[list[int|float]]) -> list[list[int|float]]:
A = np.array(A)
T = np.array(T)
S = np.array(S)
# both T and S should be invertible
try:
inv_T = np.linalg.inv(T)
inv_S = np.linalg.inv(S)
except:
return -1
transformed_matrix = np.round(inv_T @ A @ S, 3)
return transformed_matrix
原文地址:https://blog.csdn.net/bbrruunnoo/article/details/142416316
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!