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