scikits-learn pca dimension reduction issue

numpy, pca, python, scikit-learn

Solution

Call `fit_transform()` on train, `transform()` on test:

from sklearn import decomposition

train = np.random.rand(1050, 4096)
test = np.random.rand(50, 4096)

pca = decomposition.PCA()
pca.n_components = 399
train_reduced = pca.fit_transform(train)
test_reduced = pca.transform(test)

Problem

I have a problem with reduction dimension using scikit-learn and PCA. I have two numpy matrices, one has size (1050,4096) and another has size (50,4096). I tried to reduce the dimensions of both to yield (1050, 399) and (50,399) but, after doing the pca I got (1050,399) and (50,50) matrices. One matrix is for knn training and another for knn test. What's wrong with my code below? ``` pca = decomposition.PCA() pca.fit(train) pca.n_components = 399 train_reduced = pca.fit_transform(train) pca.n_components = 399 pca.fit(test) test_reduced = pca.fit_transform(test) ```

Original source