{{ message }}

Instantly share code, notes, and snippets.

# dmaniry/gist:5170087

Last active Aug 17, 2021
 import numpy as np from scipy import linalg from sklearn.utils import array2d, as_float_array from sklearn.base import TransformerMixin, BaseEstimator class ZCA(BaseEstimator, TransformerMixin): def __init__(self, regularization=10**-5, copy=False): self.regularization = regularization self.copy = copy def fit(self, X, y=None): X = array2d(X) X = as_float_array(X, copy = self.copy) self.mean_ = np.mean(X, axis=0) X -= self.mean_ sigma = np.dot(X.T,X) / X.shape U, S, V = linalg.svd(sigma) tmp = np.dot(U, np.diag(1/np.sqrt(S+self.regularization))) self.components_ = np.dot(tmp, U.T) return self def transform(self, X): X = array2d(X) X_transformed = X - self.mean_ X_transformed = np.dot(X_transformed, self.components_.T) return X_transformed

### nicolaspanel commented May 23, 2015

 Hi @duschendestroyer and thank you for sharing your code! Despite my efforts, I didn't find out how apply this method to RGB images. According to UFLDL Tutorial and to your code, I understand that `X` is supposed to be a matrix (2d-array) of `0.` to `1.` floats with shape: `(n_samples, Height * Width * 3,)`. Is that right? If so, how do you transform an original dataset with shape `(n_samples, Height, Witdh, 3)` to `(n_samples, Height * Witdh * 3)` ? do you simply reshape?

### yueranyuan commented Nov 30, 2015

 "do you simply reshape?" Yes (the answer is prob far too late but may it help anyone who stumbles on this gist via google)

### Coderx7 commented Oct 25, 2016

 How is that done in python (Im new to python)I'd be grateful if you could as well show a snippet for that.

### JaeDukSeo commented May 18, 2018

 if you are using numpy it is very easy just use https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.reshape.html

### JaeDukSeo commented May 5, 2019

 if you got the code from https://github.com/ltrottier/ZCA-Whitening-Python/blob/master/zca.py plz cite