rknnmlr

Prediction with knn model from mlr library


How to make predictions with new data? I was only able to use the predict() function with the dataset. If I have x = 62.5, how do I predict the value of y?

library(mlr)
library(tidyverse)

x <- c(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)
y <- c(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83)

dataset <- data.frame(x,y)
dataset <- as_tibble(dataset)

# (RE)DEFINING THE TASK ----
task <- makeRegrTask(data = dataset, target = "y")

# DEFINING THE K-NN LEARNER ----
kknn <- makeLearner("regr.kknn")

getParamSet(kknn)

kknnParamSpace <- makeParamSet(makeDiscreteParam("k", values = 1:10))

gridSearch <- makeTuneControlGrid()

kFold <- makeResampleDesc("CV", iters = 10)

tunedK <- tuneParams(kknn, task = task, 
                     resampling = kFold, 
                     par.set = kknnParamSpace, 
                     control = gridSearch)

tunedK

knnTuningData <- generateHyperParsEffectData(tunedK)

plotHyperParsEffect(knnTuningData, x = "k", y = "mse.test.mean",
                    plot.type = "line") +
  theme_bw()


# TRAINING FINAL MODEL WITH TUNED K ----
tunedKnn <- setHyperPars(makeLearner("regr.kknn"), par.vals = tunedK$x)

tunedKnnModel <- train(tunedKnn, task)

y<-predict(tunedKnnModel, task, type = "prob")

Solution

  • You can use the newdata argument for that; see https://mlr.mlr-org.com/articles/tutorial/predict.html.