Path: blob/master/Part 3 - Classification/Naive Bayes/classification_template.R
1009 views
# Classification template12# 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 classifier to the Training set22# Create your classifier here2324# Predicting the Test set results25y_pred = predict(classifier, newdata = test_set[-3])2627# Making the Confusion Matrix28cm = table(test_set[, 3], y_pred)2930# Visualising the Training set results31library(ElemStatLearn)32set = training_set33X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)34X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)35grid_set = expand.grid(X1, X2)36colnames(grid_set) = c('Age', 'EstimatedSalary')37y_grid = predict(classifier, newdata = grid_set)38plot(set[, -3],39main = 'Classifier (Training set)',40xlab = 'Age', ylab = 'Estimated Salary',41xlim = range(X1), ylim = range(X2))42contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)43points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))44points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))4546# Visualising the Test set results47library(ElemStatLearn)48set = test_set49X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)50X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)51grid_set = expand.grid(X1, X2)52colnames(grid_set) = c('Age', 'EstimatedSalary')53y_grid = predict(classifier, newdata = grid_set)54plot(set[, -3], main = 'Classifier (Test set)',55xlab = 'Age', ylab = 'Estimated Salary',56xlim = range(X1), ylim = range(X2))57contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)58points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))59points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))6061