Path: blob/master/Part 9 - Dimension Reduction/Kernel PCA/kernel_pca.py
1336 views
# Kernel PCA12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Social_Network_Ads.csv')9X = dataset.iloc[:, [2, 3]].values10y = dataset.iloc[:, 4].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.25, 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 Kernel PCA23from sklearn.decomposition import KernelPCA24kpca = KernelPCA(n_components = 2, kernel = 'rbf')25X_train = kpca.fit_transform(X_train)26X_test = kpca.transform(X_test)2728# Fitting Logistic Regression to the Training set29from sklearn.linear_model import LogisticRegression30classifier = LogisticRegression(random_state = 0)31classifier.fit(X_train, y_train)3233# Predicting the Test set results34y_pred = classifier.predict(X_test)3536# Making the Confusion Matrix37from sklearn.metrics import confusion_matrix38cm = confusion_matrix(y_test, y_pred)3940# Visualising the Training set results41from matplotlib.colors import ListedColormap42X_set, y_set = X_train, y_train43X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),44np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))45plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),46alpha = 0.75, cmap = ListedColormap(('red', 'green')))47plt.xlim(X1.min(), X1.max())48plt.ylim(X2.min(), X2.max())49for i, j in enumerate(np.unique(y_set)):50plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],51c = ListedColormap(('red', 'green'))(i), label = j)52plt.title('Logistic Regression (Training set)')53plt.xlabel('Age')54plt.ylabel('Estimated Salary')55plt.legend()56plt.show()5758# Visualising the Test set results59from matplotlib.colors import ListedColormap60X_set, y_set = X_test, y_test61X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),62np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))63plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),64alpha = 0.75, cmap = ListedColormap(('red', 'green')))65plt.xlim(X1.min(), X1.max())66plt.ylim(X2.min(), X2.max())67for i, j in enumerate(np.unique(y_set)):68plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],69c = ListedColormap(('red', 'green'))(i), label = j)70plt.title('Logistic Regression (Test set)')71plt.xlabel('Age')72plt.ylabel('Estimated Salary')73plt.legend()74plt.show()7576