Created
April 4, 2018 16:45
-
-
Save wsuzume/51a49eb2e41ab5db4a269da36680724c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding:utf-8 | |
import numpy as np | |
class WhiteningScaler: | |
def __init__(self, axis=0, threshold=1e-12, apply_zca=False): | |
# 行方向にデータが格納されている場合は axis=0 | |
# 列方向にデータが格納されている場合は axis=1 | |
self.axis = axis | |
self.threshold = threshold | |
# ZCAをオンにしなければ正規化されたPCAと等価 | |
self.apply_zca = apply_zca | |
pass | |
def fit(self, X): | |
# データは列方向に格納する | |
if self.axis == 0: | |
self.X = np.array(X.T) | |
else: | |
self.X = np.array(X) | |
# Centering | |
self.mean = np.mean(X, axis=1) | |
self.X = self.X - self.mean | |
# SVD | |
U, s, _ = np.linalg.svd(self.X, full_matrices=False) | |
s[s < self.threshold] = self.threshold | |
S_inv = np.diag(np.ones(s.shape) / s) | |
self.U = U | |
self.S_inv = S_inv | |
# Decorrelation | |
self.X = U.T.dot(self.X) | |
# Whitening | |
self.X = S_inv.dot(self.X) | |
# ZCA(Zero-phase Component Analysis) Whitening | |
if self.apply_zca: | |
self.X = U.dot(self.X) | |
if self.axis == 0: | |
return np.array(self.X.T) | |
else: | |
return np.array(self.X) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment