Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 10 - Model Selection And Boosting/Grid Search/grid_search.py
1339 views
1
# Grid Search
2
3
# Importing the libraries
4
import numpy as np
5
import matplotlib.pyplot as plt
6
import pandas as pd
7
8
# Importing the dataset
9
dataset = pd.read_csv('Social_Network_Ads.csv')
10
X = dataset.iloc[:, [2, 3]].values
11
y = dataset.iloc[:, 4].values
12
13
# Splitting the dataset into the Training set and Test set
14
from sklearn.model_selection import train_test_split
15
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
16
17
# Feature Scaling
18
from sklearn.preprocessing import StandardScaler
19
sc = StandardScaler()
20
X_train = sc.fit_transform(X_train)
21
X_test = sc.transform(X_test)
22
23
# Fitting Kernel SVM to the Training set
24
from sklearn.svm import SVC
25
classifier = SVC(kernel = 'rbf', random_state = 0)
26
classifier.fit(X_train, y_train)
27
28
# Predicting the Test set results
29
y_pred = classifier.predict(X_test)
30
31
# Making the Confusion Matrix
32
from sklearn.metrics import confusion_matrix
33
cm = confusion_matrix(y_test, y_pred)
34
35
# Applying k-Fold Cross Validation
36
from sklearn.model_selection import cross_val_score
37
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
38
accuracies.mean()
39
accuracies.std()
40
41
# Applying Grid Search to find the best model and the best parameters
42
from sklearn.model_selection import GridSearchCV
43
parameters = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
44
{'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]}]
45
grid_search = GridSearchCV(estimator = classifier,
46
param_grid = parameters,
47
scoring = 'accuracy',
48
cv = 10,
49
n_jobs = -1)
50
grid_search = grid_search.fit(X_train, y_train)
51
best_accuracy = grid_search.best_score_
52
best_parameters = grid_search.best_params_
53
54
# Visualising the Training set results
55
from matplotlib.colors import ListedColormap
56
X_set, y_set = X_train, y_train
57
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
58
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
59
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
60
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
61
plt.xlim(X1.min(), X1.max())
62
plt.ylim(X2.min(), X2.max())
63
for i, j in enumerate(np.unique(y_set)):
64
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
65
c = ListedColormap(('red', 'green'))(i), label = j)
66
plt.title('Kernel SVM (Training set)')
67
plt.xlabel('Age')
68
plt.ylabel('Estimated Salary')
69
plt.legend()
70
plt.show()
71
72
# Visualising the Test set results
73
from matplotlib.colors import ListedColormap
74
X_set, y_set = X_test, y_test
75
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
76
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
77
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
78
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
79
plt.xlim(X1.min(), X1.max())
80
plt.ylim(X2.min(), X2.max())
81
for i, j in enumerate(np.unique(y_set)):
82
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
83
c = ListedColormap(('red', 'green'))(i), label = j)
84
plt.title('Kernel SVM (Test set)')
85
plt.xlabel('Age')
86
plt.ylabel('Estimated Salary')
87
plt.legend()
88
plt.show()
89