使用来自 mlr 库的 knn 模型进行预测

Prediction with knn model from mlr library

如何使用新数据进行预测?我只能对数据集使用 predict() 函数。如果我有 x = 62.5,我如何预测 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")

您可以为此使用 newdata 参数;参见 https://mlr.mlr-org.com/articles/tutorial/predict.html