Sklearn Principle Component Analysis - PCA Example

Python

How to perform principle component analysis on training data, transform both the training and test data before outputting the explained variance ratio.

 1|  from sklearn.decomposition import PCA
 2|  
 3|  # Step 1: Initalise and fit PCA for 4 dimensions
 4|  pca = PCA(n_components=4)
 5|  pca.fit(X_train)
 6|  
 7|  # Step 2: Transform data
 8|  X_train = pd.DataFrame(pca.transform(X_train))
 9|  X_test = pd.DataFrame(pca.transform(X_test))
10|  
11|  # Step 3: Print out explained variance ratio
12|  print(pca.explained_variance_ratio_)
Did you find this snippet useful?

Sign up for free to to add this to your code library