-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathKNN
73 lines (65 loc) · 2.12 KB
/
KNN
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# KNN
library(caret)
library(pROC)
library(mlbench)
# Example-1 Classification
data <- read.csv('https://raw.githubusercontent.com/bkrai/Statistical-Modeling-and-Graphs-with-R/main/binary.csv')
str(data)
data$admit[data$admit == 0] <- 'no'
data$admit[data$admit == 1] <- 'yes'
data$admit <- factor(data$admit)
data$rank <- factor(data$rank)
# Data partition
set.seed(1234)
ind <- sample(2, nrow(data), replace = T, prob=c(.7, .3))
training <- data[ind==1, ]
test <- data[ind==2, ]
# K-NN
trControl <- trainControl(method = "repeatedcv", #repeated cross-validation
number = 10, # number of resampling iterations
repeats = 3, # sets of folds to for repeated cross-validation
classProbs = TRUE,
summaryFunction = twoClassSummary) # classProbs needed for ROC
set.seed(1234)
fit <- train(admit ~ .,
data = training,
tuneGrid = expand.grid(k = 1:50),
method = "knn",
tuneLength = 20,
metric = "ROC",
trControl = trControl,
preProc = c("center", "scale")) # necessary task
# Model performance
fit
plot(fit)
varImp(fit)
pred <- predict(fit, newdata = test )
confusionMatrix(pred, test$admit, positive = 'yes' )
# Example-2 Regression
data(BostonHousing)
data <- BostonHousing
str(data)
# Data partition
set.seed(1234)
ind <- sample(2, nrow(data), replace = T, prob=c(.7, .3))
training <- data[ind==1, ]
test <- data[ind==2, ]
# K-NN
trControl <- trainControl(method = "repeatedcv", #repeated cross-validation
number = 10, # number of resampling iterations
repeats = 3) # classProbs needed for ROC
set.seed(1234)
fit <- train(medv ~ .,
data = training,
tuneGrid = expand.grid(k = 1:50),
method = "knn",
tuneLength = 10,
metric = "RMSE",
trControl = trControl,
preProc = c("center", "scale"))
# Model performance
fit
plot(fit)
varImp(fit)
pred <- predict(fit, newdata = test )
RMSE(pred, test$medv)