Path: blob/master/Part 3 - Classification/Kernel SVM/kernel_svm.R
1009 views
# Kernel SVM12# Importing the dataset3dataset = read.csv('Social_Network_Ads.csv')4dataset = dataset[3:5]56# Encoding the target feature as factor7dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))89# Splitting the dataset into the Training set and Test set10# install.packages('caTools')11library(caTools)12set.seed(123)13split = sample.split(dataset$Purchased, SplitRatio = 0.75)14training_set = subset(dataset, split == TRUE)15test_set = subset(dataset, split == FALSE)1617# Feature Scaling18training_set[-3] = scale(training_set[-3])19test_set[-3] = scale(test_set[-3])2021# Fitting Kernel SVM to the Training set22# install.packages('e1071')23library(e1071)24classifier = svm(formula = Purchased ~ .,25data = training_set,26type = 'C-classification',27kernel = 'radial')2829# Predicting the Test set results30y_pred = predict(classifier, newdata = test_set[-3])3132# Making the Confusion Matrix33cm = table(test_set[, 3], y_pred)3435# Visualising the Training set results36library(ElemStatLearn)37set = training_set38X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)39X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)40grid_set = expand.grid(X1, X2)41colnames(grid_set) = c('Age', 'EstimatedSalary')42y_grid = predict(classifier, newdata = grid_set)43plot(set[, -3],44main = 'Kernel SVM (Training set)',45xlab = 'Age', ylab = 'Estimated Salary',46xlim = range(X1), ylim = range(X2))47contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)48points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))49points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))5051# Visualising the Test set results52library(ElemStatLearn)53set = test_set54X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)55X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)56grid_set = expand.grid(X1, X2)57colnames(grid_set) = c('Age', 'EstimatedSalary')58y_grid = predict(classifier, newdata = grid_set)59plot(set[, -3], main = 'Kernel SVM (Test set)',60xlab = 'Age', ylab = 'Estimated Salary',61xlim = range(X1), ylim = range(X2))62contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)63points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))64points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))6566