ML | Principal Component Analysis(PCA)
Principal Component Analysis (PCA) is a statistical procedure that uses an orthogonal transformation that converts a set of correlated variables to a set of uncorrelated variables. PCA is the most widely used tool in exploratory data analysis and in machine learning for predictive models. Moreover, PCA is an unsupervised statistical technique used to examine the interrelations among a set of variables. It is also known as a general factor analysis where regression determines a line of best fit.
Module Needed:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline |
Code #1:
# Here we are using inbuilt dataset of scikit learnfrom sklearn.datasets import load_breast_cancer # instantiatingcancer = load_breast_cancer() # creating dataframedf = pd.DataFrame(cancer['data'], columns = cancer['feature_names']) # checking head of dataframedf.head() |
Output:

Code #2:
# Importing standardscalar module from sklearn.preprocessing import StandardScaler scalar = StandardScaler() # fittingscalar.fit(df)scaled_data = scalar.transform(df) # Importing PCAfrom sklearn.decomposition import PCA # Let's say, components = 2pca = PCA(n_components = 2)pca.fit(scaled_data)x_pca = pca.transform(scaled_data) x_pca.shape |
Output:
569, 2
# giving a larger plotplt.figure(figsize =(8, 6)) plt.scatter(x_pca[:, 0], x_pca[:, 1], c = cancer['target'], cmap ='plasma') # labeling x and y axesplt.xlabel('First Principal Component')plt.ylabel('Second Principal Component') |
Output:

# componentspca.components_ |
Output:

df_comp = pd.DataFrame(pca.components_, columns = cancer['feature_names']) plt.figure(figsize =(14, 6)) # plotting heatmapsns.heatmap(df_comp) |
Output:




