Skip to content

Instantly share code, notes, and snippets.

@chairco
Created December 26, 2018 00:36
Show Gist options
  • Save chairco/2745a87dc38faf3539f701c0bb418180 to your computer and use it in GitHub Desktop.
Save chairco/2745a87dc38faf3539f701c0bb418180 to your computer and use it in GitHub Desktop.
import numpy as np
def normalize(X):
"""數據標準化處理
Args:
X 樣本
Returns:
XNorm 標準化後的樣本
"""
XNorm = X.copy()
m,n = XNorm.shape
mean = np.mean(XNorm, axis=0)
std = np.std(XNorm, axis=0)
XNorm = (XNorm - mean) / std
return XNorm
def PCA(X, k = 1):
"""PCA
Args:
X 樣本
k 目的維度
Returns:
XNorm 標準化後的樣本
Z 降維後的新樣本
U U
UReduce UReduce
S S
V V
"""
m, n = X.shape
# 數據歸一化
XNorm = normalize(X)
# 計算協方差矩陣
Coef = XNorm.T * XNorm/m
# 奇異值分解
U, S, V = np.linalg.svd(Coef)
# 取出前 k 個向量
UReduce = U[:, 0:k]
Z = XNorm * UReduce
return XNorm, Z, U, UReduce, S, V
def recover(UReduce, Z):
"""數據恢復
Args:
UReduce UReduce
Z 降維後的樣本
"""
return Z * UReduce.T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment