-
Notifications
You must be signed in to change notification settings - Fork 4
/
K Nearest Neighbors.Rmd
121 lines (87 loc) · 1.76 KB
/
K Nearest Neighbors.Rmd
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
---
output:
word_document: default
html_document: default
---
### K Nearest Neighbor
```{r}
library(ISLR)
str(Caravan)
summary(Caravan$Purchase)
```
```{r}
any(is.na(Caravan))
```
```{r}
var(Caravan[,1])
var(Caravan[,2])
```
```{r}
purchase <- Caravan[,86]
```
# Standardize Dataset in R
```{r}
standardized.Caravan <- scale(Caravan[,-86])
print(var(standardized.Caravan[,1]))
print(var(standardized.Caravan[,2]))
```
# Test
```{r}
test.index <- 1:1000
test.data <- standardized.Caravan[test.index,]
test.purchase <- purchase[test.index]
```
# Train
```{r}
train.data <- standardized.Caravan[-test.index,]
train.purchase <- purchase[-test.index]
```
# KNN Model
```{r}
library(class)
```
```{r}
set.seed(101)
predicted.purchase <- knn(train.data,test.data,train.purchase,k=1)
print(head(predicted.purchase))
```
# Using Different K value Where k=3
```{r}
predicted.purchase <- knn(train.data,test.data,train.purchase,k=3)
mean(test.purchase != predicted.purchase)
```
# k=5
```{r}
predicted.purchase <- knn(train.data,test.data,train.purchase,k=5)
mean(test.purchase != predicted.purchase)
```
# Null vs. NA
```{r}
predicted.purchase = NULL
error.rate = NULL
```
```{r}
for(i in 1:20){
set.seed(101)
predicted.purchase = knn(train.data,test.data,train.purchase,k=i)
error.rate[i] = mean(test.purchase != predicted.purchase)
}
```
```{r}
print(error.rate)
```
# Elbow Method
```{r}
library(ggplot2)
```
```{r}
k.values <- 1:20
```
```{r}
error.df <- data.frame(error.rate,k.values)
error.df
```
# Determining Misclassification
```{r}
ggplot(error.df,aes(x=k.values,y=error.rate)) + geom_point()+ geom_line(lty="dotted",color='red')
```