Skip to content

Instantly share code, notes, and snippets.

@devbruce
Last active July 18, 2022 04:37
Show Gist options
  • Save devbruce/85f47dfa6eac3e077072ac6246245d68 to your computer and use it in GitHub Desktop.
Save devbruce/85f47dfa6eac3e077072ac6246245d68 to your computer and use it in GitHub Desktop.
Implementation functions of Linear Algebra
import numpy as np
__all__ = ['get_cos_sim', 'apply_svd']
def get_cos_sim(v1:np.ndarray, v2:np.ndarray) -> np.float64:
cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
return cos_sim
def apply_svd(matrix:np.ndarray, k:int) -> tuple:
"""
Args:
matrix (np.ndarray): shape (m, n)
k (int): Number of latent features
Returns:
tuple: U(m, k), Sigma(k, k), VT(k, n)
"""
U, Sigma, VT = np.linalg.svd(matrix) # Current shape: U(m, m), Sigma(n,), VT(n, n)
U_truncated = U[:, :k] # Shape: (m, k)
Sigma_truncated = np.diag(Sigma[:k]) # Shape: (k, k)
VT_truncated = VT[:k] # Shape: (k, n)
return U_truncated, Sigma_truncated, VT_truncated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment