9951 explained code solutions for 126 technologies


python-scikit-learnPCA dimensionality reduction example


from sklearn import decomposition, datasets

X, y = datasets.load_iris(return_X_y=True)
pca = decomposition.PCA(n_components=3)

pca.fit(X)
X = pca.transform(X)ctrl + c
from sklearn import

import module from scikit-learn

load_iris

loads Iris dataset

decomposition.PCA(

create PCA dimensionality reduction model

n_components

reduce to the given number of components (3 in our case)

.fit(

train reduction model model

.transform(

transform original data and return reduced dimensions data


Usage example

from sklearn import decomposition, datasets

X, y = datasets.load_iris(return_X_y=True)
print('Original:', X.shape)

pca = decomposition.PCA(n_components=3)
pca.fit(X)
X = pca.transform(X)

print('Reduced: ', X.shape)
output
Original: (150, 4)
Reduced:  (150, 3)