Path: blob/master/Part 3 - Classification/K Nearest Neighbors/knn.R
1009 views
# K-Nearest Neighbors (K-NN)12# 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 K-NN to the Training set and Predicting the Test set results22library(class)23y_pred = knn(train = training_set[, -3],24test = test_set[, -3],25cl = training_set[, 3],26k = 5,27prob = TRUE)2829# Making the Confusion Matrix30cm = table(test_set[, 3], y_pred)3132# Visualising the Training set results33library(ElemStatLearn)34set = training_set35X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)36X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)37grid_set = expand.grid(X1, X2)38colnames(grid_set) = c('Age', 'EstimatedSalary')39y_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)40plot(set[, -3],41main = 'K-NN (Training set)',42xlab = 'Age', ylab = 'Estimated Salary',43xlim = range(X1), ylim = range(X2))44contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)45points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))46points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))4748# Visualising the Test set results49library(ElemStatLearn)50set = test_set51X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)52X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)53grid_set = expand.grid(X1, X2)54colnames(grid_set) = c('Age', 'EstimatedSalary')55y_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)56plot(set[, -3],57main = 'K-NN (Test set)',58xlab = 'Age', ylab = 'Estimated Salary',59xlim = range(X1), ylim = range(X2))60contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)61points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))62points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))6364