Path: blob/master/Part 10 - Model Selection And Boosting/Grid Search/grid_search.py
1339 views
# Grid Search12# 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# Fitting Kernel SVM to the Training set23from sklearn.svm import SVC24classifier = SVC(kernel = 'rbf', random_state = 0)25classifier.fit(X_train, y_train)2627# Predicting the Test set results28y_pred = classifier.predict(X_test)2930# Making the Confusion Matrix31from sklearn.metrics import confusion_matrix32cm = confusion_matrix(y_test, y_pred)3334# Applying k-Fold Cross Validation35from sklearn.model_selection import cross_val_score36accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)37accuracies.mean()38accuracies.std()3940# Applying Grid Search to find the best model and the best parameters41from sklearn.model_selection import GridSearchCV42parameters = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']},43{'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}]44grid_search = GridSearchCV(estimator = classifier,45param_grid = parameters,46scoring = 'accuracy',47cv = 10,48n_jobs = -1)49grid_search = grid_search.fit(X_train, y_train)50best_accuracy = grid_search.best_score_51best_parameters = grid_search.best_params_5253# Visualising the Training set results54from matplotlib.colors import ListedColormap55X_set, y_set = X_train, y_train56X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),57np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))58plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),59alpha = 0.75, cmap = ListedColormap(('red', 'green')))60plt.xlim(X1.min(), X1.max())61plt.ylim(X2.min(), X2.max())62for i, j in enumerate(np.unique(y_set)):63plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],64c = ListedColormap(('red', 'green'))(i), label = j)65plt.title('Kernel SVM (Training set)')66plt.xlabel('Age')67plt.ylabel('Estimated Salary')68plt.legend()69plt.show()7071# Visualising the Test set results72from matplotlib.colors import ListedColormap73X_set, y_set = X_test, y_test74X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),75np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))76plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),77alpha = 0.75, cmap = ListedColormap(('red', 'green')))78plt.xlim(X1.min(), X1.max())79plt.ylim(X2.min(), X2.max())80for i, j in enumerate(np.unique(y_set)):81plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],82c = ListedColormap(('red', 'green'))(i), label = j)83plt.title('Kernel SVM (Test set)')84plt.xlabel('Age')85plt.ylabel('Estimated Salary')86plt.legend()87plt.show()8889