Docsity

ISYE 6501 Course homework assignment one solution, Assignments of Data Representation and Algorithm Design

Toggle sidebar
bg1
question 2.2 - knn
#install.packages("kknn")
library(kknn)
Read the file
data <- read.table("/Users/marylin/Downloads/hw1/data 2.2/credit_card_data-headers.txt",header=TRUE)
Set up predictors and response
x<- data[, -11]
y<- data[,11]
Call kknn
k<- 8
y_pred <- vector("integer",length(y))
#exclude i in the nearest neighbor
for (i in 1:nrow(data)) {
train_x <- as.matrix(data[, -11])
train_y <- data[,11]
train_data <- data.frame(train_x, R1=train_y)
test_X <- data[i, -11, drop=FALSE]
test_data <- data.frame(test_X)
#kknn
knn_model <- kknn(R1 ~., train_data, test_data, k=k, kernel="rectangular")
#predict
y_pred[i] <- as.integer(fitted(knn_model))
}
Calculate how good the classifier is
accuracy <- sum(y_pred == y) /length(y)
confusion_matrix <- data.frame(y, y_pred)
precision <- confusion_matrix[2,2]/sum(confusion_matrix[,2])
recall <- confusion_matrix[2,2]/sum(confusion_matrix[2,])
f1 <- 2*(precision *recall) /(precision +recall)
Print the output
1
pf2

Partial preview of the text

Download ISYE 6501 Course homework assignment one solution and more Assignments Data Representation and Algorithm Design in PDF only on Docsity!

question 2.2 - knn

#install.packages("kknn") library (kknn)

Read the file

data <- read.table ("/Users/marylin/Downloads/hw1/data 2.2/credit_card_data-headers.txt", header=TRUE)

Set up predictors and response

x <- data[, - 11] y <- data[,11]

Call kknn

k <- 8 y_pred <- vector ("integer", length (y))

#exclude i in the nearest neighbor for (i in 1 :nrow (data)) { train_x <- as.matrix (data[, - 11]) train_y <- data[,11]

train_data <- data.frame (train_x, R1 = train_y)

test_X <- data[i, - 11, drop=FALSE] test_data <- data.frame (test_X)

#kknn knn_model <- kknn (R1 ~ ., train_data, test_data, k=k, kernel="rectangular")

#predict y_pred[i] <- as.integer ( fitted (knn_model)) }

Calculate how good the classifier is

accuracy <- sum (y_pred == y) / length (y)

confusion_matrix <- data.frame (y, y_pred) precision <- confusion_matrix[2,2] / sum (confusion_matrix[,2]) recall <- confusion_matrix[2,2] / sum (confusion_matrix[2,]) f1 <- 2 ***** (precision ***** recall) / (precision + recall)

Print the output

accuracy

## [1] 0.

precision

## [1] 0.

recall

## [1] 0.

f

## [1] 0.