11
votes

Let me keep this brief. Basically what I want to know is: should I do this,

pca.fit(normalize(x))
new=pca.transform(normalize(x))

or this

pca.fit(normalize(x))
new=pca.transform(x)

I know that we should normalize our data before using PCA but which one of the procedures above is correct with sklearn?

1
What type of normalization do you mean exactly? I added an answer where I standardize the data before PCA, but you can choose other types of normalization even with that same object. - eickenberg
To fit to and then transform the same data, use fit_transform. It's more efficient, esp. for PCA which computes the transformation as part of its training step. - Fred Foo
I have asked a followup question for when you want to normalize for PCA on all data, but apply this PCA on data separately. So the question is about how to normalize the separately data: stackoverflow.com/questions/27646915/… - NumesSanguis

1 Answers

21
votes

In general, you would want to use the first option.

Your normalization places your data in a new space which is seen by the PCA and its transform basically expects the data to be in the same space.

Scikit-learn provides tools to do this transparently and conveniently by concatenating estimators in a pipeline. Try:

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline

import numpy as np

data = np.random.randn(20, 40)

pipeline = Pipeline([('scaling', StandardScaler()), ('pca', PCA(n_components=5))])

pipeline.fit_transform(data)

The prepended scaler will then always apply its transformation to the data before it goes to the PCA object.

As @larsmans points out, you may want to use sklearn.preprocessing.Normalizer instead of the StandardScaler or, similarly, remove the mean centering from the StandardScaler by passing the keyword argument with_mean=False.