Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 3 - Classification/Decision Tree/classification_template.R
1009 views
1
# Classification template
2
3
# Importing the dataset
4
dataset = read.csv('Social_Network_Ads.csv')
5
dataset = dataset[3:5]
6
7
# Encoding the target feature as factor
8
dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))
9
10
# Splitting the dataset into the Training set and Test set
11
# install.packages('caTools')
12
library(caTools)
13
set.seed(123)
14
split = sample.split(dataset$Purchased, SplitRatio = 0.75)
15
training_set = subset(dataset, split == TRUE)
16
test_set = subset(dataset, split == FALSE)
17
18
# Feature Scaling
19
training_set[-3] = scale(training_set[-3])
20
test_set[-3] = scale(test_set[-3])
21
22
# Fitting classifier to the Training set
23
# Create your classifier here
24
25
# Predicting the Test set results
26
y_pred = predict(classifier, newdata = test_set[-3])
27
28
# Making the Confusion Matrix
29
cm = table(test_set[, 3], y_pred)
30
31
# Visualising the Training set results
32
library(ElemStatLearn)
33
set = training_set
34
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
35
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
36
grid_set = expand.grid(X1, X2)
37
colnames(grid_set) = c('Age', 'EstimatedSalary')
38
y_grid = predict(classifier, newdata = grid_set)
39
plot(set[, -3],
40
main = 'Classifier (Training set)',
41
xlab = 'Age', ylab = 'Estimated Salary',
42
xlim = range(X1), ylim = range(X2))
43
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
44
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
45
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
46
47
# Visualising the Test set results
48
library(ElemStatLearn)
49
set = test_set
50
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
51
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
52
grid_set = expand.grid(X1, X2)
53
colnames(grid_set) = c('Age', 'EstimatedSalary')
54
y_grid = predict(classifier, newdata = grid_set)
55
plot(set[, -3], main = 'Classifier (Test set)',
56
xlab = 'Age', ylab = 'Estimated Salary',
57
xlim = range(X1), ylim = range(X2))
58
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
59
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
60
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
61