r - Error in kNN classification code -
i writing knn classification code scratch , data set used cancer data set (standard machine learning) attaching r code, have tried umpteen times unable find error in code classifying in "benign" new apologize if there error in posting such here
r code:
# creating function knn classification method knn <- function(train,test,k,train_labels,test_labels) { # initializing vector classification classified_vector <- c() # need take transpose of test first make work transpose_test <- t(test) # taking transpose of main transpose_train <- t(train) #here need intitalize test set for(i in 1:nrow(test)) { observation <- transpose_test[,i] # have done choosen 1st line # need find distance of first line other points in train set xy2_matrix <- (transpose_train-observation)^2 # given have (x-y)^2 need add them , square root #individual distances dist_xy <- sqrt(apply(xy2_matrix,2,sum)) # need sort them kth minimum distance sort_dist_xy <- sort(dist_xy) cutoff <- sort_dist_xy[k] # finding values below cutoff limit # have create new function rownumbers , apply distance # using function rownumbers , finding labels dist_data.frame <- data.frame(dist_xy) rows <- apply(dist_data.frame,1,rownumbers,cutoff) # have rows use in labels table_factors <- table(train_labels[rows]) if(table_factors[1]<table_factors[2]) classified_vector <- c(classified_vector,"b") else classified_vector <- c(classified_vector,"m") } return(classified_vector) } rownumbers <- function(distance,cutof) { if(distance <= cutof) distance <-1 else distance <-0 return(distance) }
Comments
Post a Comment