-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkNN.Rmd
More file actions
70 lines (47 loc) · 1.5 KB
/
Copy pathkNN.Rmd
File metadata and controls
70 lines (47 loc) · 1.5 KB
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
---
title: "kNN"
author: "Tom"
date: "October 20, 2015"
output: html_document
---
#Knn (k-Nearest-Neighbors)
This is an example of knn classification from a class I took. kNN is an algorithm that makes predictions based off of the nearest points. The scientist must specify the parameter k, which is the number of clusters the algorithm will assume are present.
###Setup
```{r}
library(ggplot2)
library(class)
library(plyr)
library(dplyr)
```
###Read Data and produce summary statistics
```{r}
iris <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"), header = F)
names(iris) <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")
summary(iris)
```
###Descriptive Plots
```{r}
pl <- ggplot(data = iris) +
geom_point(aes(x = Sepal.Width,y = Sepal.Length, colour = Species))
print(pl)
pl <- ggplot(data = iris) +
geom_point(aes(x = Petal.Width,y = Petal.Length, colour = Species))
print(pl)
```
###Create kNN Model
```{r}
set.seed(55)
# Splitting the data into training and test (this line finds indeces for split)
ind <- sample(2, nrow(iris), replace = T, prob = c(0.67, .33))
# Training Data
iris.training <- iris[ind == 1, 1:4]
# Test Data
iris.test <- iris[ind == 2, 1:4]
# Labels (Species)
iris.training.labels <- iris[ind == 1, 5]
iris.test.labels <- iris[ind == 2, 5]
iris.pred <- knn(iris.training, iris.test, cl = iris.training.labels, k =3)
iris.pred
library(gmodels)
CrossTable(x = iris.test.labels, y = iris.pred, prop.chisq = F)
```