Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 3 - Classification/Decision Tree/decision_tree_classification.R
1009 views
1
# Decision Tree Classification
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 Decision Tree Classification to the Training set
23
# install.packages('rpart')
24
library(rpart)
25
classifier = rpart(formula = Purchased ~ .,
26
data = training_set)
27
28
# Predicting the Test set results
29
y_pred = predict(classifier, newdata = test_set[-3], type = 'class')
30
31
# Making the Confusion Matrix
32
cm = table(test_set[, 3], y_pred)
33
34
# Visualising the Training set results
35
library(ElemStatLearn)
36
set = training_set
37
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
38
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
39
grid_set = expand.grid(X1, X2)
40
colnames(grid_set) = c('Age', 'EstimatedSalary')
41
y_grid = predict(classifier, newdata = grid_set, type = 'class')
42
plot(set[, -3],
43
main = 'Decision Tree Classification (Training set)',
44
xlab = 'Age', ylab = 'Estimated Salary',
45
xlim = range(X1), ylim = range(X2))
46
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
47
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
48
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
49
50
# Visualising the Test set results
51
library(ElemStatLearn)
52
set = test_set
53
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
54
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
55
grid_set = expand.grid(X1, X2)
56
colnames(grid_set) = c('Age', 'EstimatedSalary')
57
y_grid = predict(classifier, newdata = grid_set, type = 'class')
58
plot(set[, -3], main = 'Decision Tree Classification (Test set)',
59
xlab = 'Age', ylab = 'Estimated Salary',
60
xlim = range(X1), ylim = range(X2))
61
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
62
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
63
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
64
65
# Plotting the tree
66
plot(classifier)
67
text(classifier)
68