Path: blob/master/Part 9 - Dimension Reduction/Principal Component Analysis/pca.py
1336 views
# PCA12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Wine.csv')9X = dataset.iloc[:, 0:13].values10y = dataset.iloc[:, 13].values1112# Splitting the dataset into the Training set and Test set13from sklearn.model_selection import train_test_split14X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)1516# Feature Scaling17from sklearn.preprocessing import StandardScaler18sc = StandardScaler()19X_train = sc.fit_transform(X_train)20X_test = sc.transform(X_test)2122# Applying PCA23from sklearn.decomposition import PCA24pca = PCA(n_components = 2)25X_train = pca.fit_transform(X_train)26X_test = pca.transform(X_test)27explained_variance = pca.explained_variance_ratio_2829# Fitting Logistic Regression to the Training set30from sklearn.linear_model import LogisticRegression31classifier = LogisticRegression(random_state = 0)32classifier.fit(X_train, y_train)3334# Predicting the Test set results35y_pred = classifier.predict(X_test)3637# Making the Confusion Matrix38from sklearn.metrics import confusion_matrix39cm = confusion_matrix(y_test, y_pred)4041# Visualising the Training set results42from matplotlib.colors import ListedColormap43X_set, y_set = X_train, y_train44X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),45np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))46plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),47alpha = 0.75, cmap = ListedColormap(('red', 'green', 'blue')))48plt.xlim(X1.min(), X1.max())49plt.ylim(X2.min(), X2.max())50for i, j in enumerate(np.unique(y_set)):51plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],52c = ListedColormap(('red', 'green', 'blue'))(i), label = j)53plt.title('Logistic Regression (Training set)')54plt.xlabel('PC1')55plt.ylabel('PC2')56plt.legend()57plt.show()5859# Visualising the Test set results60from matplotlib.colors import ListedColormap61X_set, y_set = X_test, y_test62X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),63np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))64plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),65alpha = 0.75, cmap = ListedColormap(('red', 'green', 'blue')))66plt.xlim(X1.min(), X1.max())67plt.ylim(X2.min(), X2.max())68for i, j in enumerate(np.unique(y_set)):69plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],70c = ListedColormap(('red', 'green', 'blue'))(i), label = j)71plt.title('Logistic Regression (Test set)')72plt.xlabel('PC1')73plt.ylabel('PC2')74plt.legend()75plt.show()7677