New classification in Machine Learning KNN model

This is my example of KNN model (I write it using R):

library(gmodels)
library(caret)
library(class)

db_class - iris

row_train - sample(nrow(db_class),nrow(db_class)*0.8)
db_train_x - db_class[row_train,-ncol(db_class)]
db_train_y - db_class[row_train,ncol(db_class)]
db_test_x - db_class[-row_train,-ncol(db_class)]
db_test_y - db_class[-row_train,ncol(db_class)]

model_knn - knn(db_train_x,db_test_x,db_train_y,12)

summary(model_knn)

CrossTable(x=db_test_y,y=model_knn,prop.chisq = FALSE)
confusionMatrix(data=factor(model_knn),reference=factor(db_test_y))

So, this is a supervised KNN models. How can I classify a new registration? I have this new registration:

new_record - c(5.3,3.2,2.0,0.2)

How can I classify it using the previous model?

Topic k-nn supervised-learning r machine-learning

Category Data Science


  1. You can use the general train from caret to train the model
  2. The new entry needs to be added in the form of the Train set, only then it will be able to predict

I would have done this like this:

library(caret)

model_knn<-train(Species ~ ., data = db_class[row_train,], method = "knn",tuneLength = 10)

#You can select any other tune length too. This is just an example.
#You can even choose to preprocess the data, with the train parameter

Now you will have to convert the new_record to a suitable data frame:

new_record <- c(5.3,3.2,2.0,0.2)

test_data <- NULL

i<-1

while (i <= length(new_record)) {
  test_data <- cbind(new_record[i], test_data)
  i<- i+1
}

colnames(test_data)<-colnames(db_class)[1:4]

Now you can make the prediction:

predict(model_knn, newdata=test_data)

[1] versicolor
Levels: setosa versicolor virginica

Prediction using your test data:

predict(model_knn, newdata=db_test_x)
 [1] setosa     setosa     setosa     setosa     setosa     setosa     setosa     versicolor
 [9] versicolor versicolor versicolor versicolor versicolor versicolor versicolor versicolor
[17] versicolor versicolor versicolor versicolor virginica  versicolor virginica  virginica 
[25] virginica  virginica  virginica  virginica  versicolor virginica 
Levels: setosa versicolor virginica

Does this solve your purpose?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.