How to do it...

Learning groupings within data and classifying with kNN can be done using the following steps:

  1. Scale the data and remove non-numeric columns:
set.seed(123)
scaled_iris <- iris %>% mutate_if( is.numeric, .funs = scale)
labels <- scaled_iris$Species scaled_iris$Species <- NULL
  1. Extract a training and test dataset:
train_rows <- sample(nrow(scaled_iris), 0.8 * nrow(scaled_iris), replace = FALSE)
train_set <- scaled_iris[train_rows, ] test_set <- scaled_iris[-train_rows, ] train_labels <- labels[train_rows] test_set_labels <- labels[-train_rows]

  1. Make the model and predictions on the test set:
test_set_predictions <- knn(train = train_set, test = test_set, cl = train_labels, k = 10)
  1. Compare the prediction with the actual class:
caret::confusionMatrix(test_set_predictions,  test_set_labels)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.254.111