<jupyter_start><jupyter_text>Principal Component Analysis (PCA) on Iris Dataset<jupyter_code>import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, accuracy_score
dataset = pd.read_csv('C:\\Users\\black\\Desktop\\ml_py\\datasets\\iris.csv', header="infer")
dataset.head()
X = dataset.drop('species', 1)
Y = dataset['species']
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
pca = PCA()
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)

explained_variance = pca.explained_variance_ratio_
explained_variance
for n in range(1, len(X.columns) + 1):
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
    
    pca = PCA(n_components=n)
    X_train = pca.fit_transform(X_train)
    X_test = pca.transform(X_test)
    
    classifier = RandomForestClassifier(max_depth=2, random_state=0)
    classifier.fit(X_train, Y_train)
    Y_pred = classifier.predict(X_test)
    
    cm = confusion_matrix(Y_test, Y_pred)
    print("Confusuion Matrix with {0} Principle Components: ".format(n))
    print(cm)
    print("Accuracy Score with {0} Principle Components: ".format(n), end="")
    print(accuracy_score(Y_test, Y_pred), end="\n\n")<jupyter_output>Confusuion Matrix with 1 Principle Components: 
[[11  0  0]
 [ 0 12  1]
 [ 0  2  4]]
Accuracy Score with 1 Principle Components: 0.9

Confusuion Matrix with 2 Principle Components: 
[[11  0  0]
 [ 0  8  5]
 [ 0  1  5]]
Accuracy Score with 2 Principle Components: 0.8

Confusuion Matrix with 3 Principle Components: 
[[11  0  0]
 [ 0  5  8]
 [ 0  1  5]]
Accuracy Score with 3 Principle Components: 0.7

Confusuion Matrix with 4 Principle Components: 
[[11  0  0]
 [ 0 11  2]
 [ 0  1  5]]
Accuracy Score with 4 Principle Components: 0.9
StarcoderdataJupyterStructuredCleanDedup