Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 3 - Classification/Random Forest/classification_template.py
1009 views
1
# Classification template
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.cross_validation 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 classifier to the Training set
24
# Create your classifier here
25
26
# Predicting the Test set results
27
y_pred = classifier.predict(X_test)
28
29
# Making the Confusion Matrix
30
from sklearn.metrics import confusion_matrix
31
cm = confusion_matrix(y_test, y_pred)
32
33
# Visualising the Training set results
34
from matplotlib.colors import ListedColormap
35
X_set, y_set = X_train, y_train
36
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
37
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
38
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
39
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
40
plt.xlim(X1.min(), X1.max())
41
plt.ylim(X2.min(), X2.max())
42
for i, j in enumerate(np.unique(y_set)):
43
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
44
c = ListedColormap(('red', 'green'))(i), label = j)
45
plt.title('Classifier (Training set)')
46
plt.xlabel('Age')
47
plt.ylabel('Estimated Salary')
48
plt.legend()
49
plt.show()
50
51
# Visualising the Test set results
52
from matplotlib.colors import ListedColormap
53
X_set, y_set = X_test, y_test
54
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
55
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
56
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
57
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
58
plt.xlim(X1.min(), X1.max())
59
plt.ylim(X2.min(), X2.max())
60
for i, j in enumerate(np.unique(y_set)):
61
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
62
c = ListedColormap(('red', 'green'))(i), label = j)
63
plt.title('Classifier (Test set)')
64
plt.xlabel('Age')
65
plt.ylabel('Estimated Salary')
66
plt.legend()
67
plt.show()
68