SHARE
TWEET

Untitled

a guest Mar 22nd, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. from sklearn.base import BaseEstimator, TransformerMixin
  3.  
  4. class Decorrelator(BaseEstimator, TransformerMixin):
  5.     def __init__(self):
  6.         pass
  7.  
  8.     def fit(self, X):
  9.         self.means = np.mean(X, axis=0)
  10.         self.covmat = np.cov(X, rowvar=False, bias=True)
  11.         self.cov_eig_vals, self.cov_eig_vecs = np.linalg.eig(self.covmat)
  12.         return self
  13.  
  14.     def transform(self, X, zero_div_eps=1e-5):
  15.         centered = X - self.means
  16.         decorrelated = centered.dot(self.cov_eig_vecs)
  17.  
  18.         self.sqrt_cov_eig_vals = np.sqrt(self.cov_eig_vals + zero_div_eps)
  19.  
  20.         rescaled = decorrelated / self.sqrt_cov_eig_vals
  21.         return rescaled
  22.  
  23.     def inverse_transform(self, X):
  24.         if getattr(self, 'sqrt_cov_eig_vals', None) is None:
  25.             raise Exception('First transform, then inverse')
  26.  
  27.         rescaled = X * self.sqrt_cov_eig_vals
  28.         decorrelated = rescaled.dot(self.cov_eig_vecs.T)
  29.         centered = decorrelated + self.means
  30.         return centered
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top