-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomework1.R
More file actions
157 lines (123 loc) · 4.03 KB
/
Homework1.R
File metadata and controls
157 lines (123 loc) · 4.03 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# Homework 1 - Jake Mathews
# Utility methods
edistance <- function(x, y) {
n = length(x)
d = 0
for (i in 1:n) {
d = d + (x[,i] - y[,i]) ^ 2
}
d = sqrt(d)
return(d)
}
######## Problem 1 ########
knn = 3
data("iris")
colnames(iris)[5] <- "Species.Name"
# Map species to a value
speciesNames = c("setosa", "versicolor", "virginica")
speciesCount = length(speciesNames)
for (speciesIndex in 1:speciesCount) {
name = speciesNames[speciesIndex]
iris$Species.Int[iris$Species.Name == name] <- speciesIndex
}
# Seperate training and test sets
trainIrisIndex <- sample(1:nrow(iris), as.integer(.7 * nrow(iris)), replace = FALSE)
trainIris <- iris[trainIrisIndex,]
testIris <- iris[-trainIrisIndex,]
# Remove species as a column to calculate distance
trainIris.no_species <- trainIris[,-5]
testIris.no_species <- testIris[,-5]
predictions <- numeric()
for (testIndex in 1:nrow(testIris)) {
distances <- numeric()
test <- testIris.no_species[testIndex,]
for (trainIndex in 1:nrow(trainIris)) {
train <- trainIris.no_species[trainIndex,]
distance <- edistance(test, train)
distances[trainIndex] = distance
}
# Create a sorted data frame with distances mapped to species
distances <- data.frame(distances, trainIris$Species.Int)
colnames(distances) <- c("distance", "species")
distances.sorted <- distances[order(distances$distance),]
# The occurance of each species is tallied
occurance <- numeric(speciesCount)
for (neighborIndex in 1:knn) {
speciesIndex = distances.sorted[neighborIndex,]$species
occurance[speciesIndex] <- occurance[speciesIndex] + 1
}
# Which ever species occured the most in the k nearest neighbors wins
# In the event of a tie, the first species in this order wins (setosa, versicolor, virginica)
predictedSpecies = which.max(occurance)
predictions[testIndex] = predictedSpecies
}
# Load result into a data frame
results <- data.frame(predictions, testIris$Species.Int)
colnames(results) <- c("predicted", "actual")
# Create confusion matrix
matrixSize = speciesCount ^ 2
confusionMatrix = matrix(numeric(matrixSize), nrow = speciesCount, ncol = speciesCount)
rownames(confusionMatrix) <- speciesNames
colnames(confusionMatrix) <- speciesNames
# Fill confusion matrix
for (resultIndex in 1:nrow(results)) {
result <- results[resultIndex,]
confusionMatrix[result$actual, result$predicted] = confusionMatrix[result$actual, result$predicted] + 1
}
matrixDiaganol <- diag(confusionMatrix)
sumTotal <- sum(confusionMatrix)
sumDiagnanol <- sum(matrixDiaganol)
#calculate accuracy
overallAccuracy <- sumDiagnanol/sumTotal
#calculate realtive error
overallError <- (sumTotal-sumDiagnanol)/sumTotal
overall <- data.frame(overallAccuracy, overallError)
colnames(overall) <- c("Accuracy", "Error")
rownames(overall) <- c("Overall")
# Print results
accuracyTable <- matrix(nrow = speciesCount, ncol = 4)
colnames(accuracyTable) <- c("TP", "FN", "FP", "TN")
rownames(accuracyTable) <- speciesNames
for (species in 1:speciesCount) {
TP = confusionMatrix[species,species]
FN = sum(confusionMatrix[species,]) - TP
FP = sum(confusionMatrix[,species]) - TP
TN = FN + FP
accuracyTable[species,] = c(TP, FN, FP, TN)
}
print("Problem 1")
print(results)
print(accuracyTable)
print(overall)
######## Problem 2 ########
library(Matrix)
library(DMwR)
library(class)
library(TTR)
acc <- numeric()
err <- numeric()
n <- integer()
datatr <- read.csv(file="pendigits_tra.csv",as.is=TRUE)
datate <- read.csv(file="pendigits_tes.csv",as.is=TRUE)
for (i in 1:100) {
n[i]=i
knear <- kNN(digit~.,datatr, datate, k=i)
#confusion matrix
t <- table(datate[,'digit'],knear)
#print(t)
#get diagonal elements of matrix
td <- diag(t)
#sum all the elements of the matrix t which gives
#the examples tested
sumt <- sum(t)
#some the diagonal to see how many we got correct
sumtd <- sum(td)
#calculate accuracy
acc[i] <- sumtd/sumt
#calculate realtive error
err[i] <- (sumt-sumtd)/sumt
#print(acc[i])
#print(err[i])
}
resultsknn <- cbind(n,acc,err)
colnames(resultsknn) <- c("k","Accuracy","Error")