Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

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

ISYE 6501 Course homework assignment one solution

Typology: Assignments

2023/2024

Uploaded on 06/15/2025

daniel-rong
daniel-rong 🇨🇦

5 documents

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

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.