0

在这里使用lmr3verse包。假设我对用于训练的训练集应用了以下预处理Learner

preprocess <- po("scale", param_vals = list(center = TRUE, scale = TRUE)) %>>%
              po("encode",param_vals = list(method = "one-hot"))

我想使用命令预测数据框中(带有原始变量)中包含的新观察结果的pred标签predict(Learner, newdata = pred, predict_type="prob")。这是行不通的,因为Learner它是使用居中、缩放和单热编码变量进行训练的。

如何将训练集上使用的相同预处理应用于新数据(仅特征,而不是响应)以进行预测?

4

2 回答 2

2

I am not 100% sure but it seems you can feed newdata to a new task and feed it to predict. This page shows an example of combining mlr_pipeops and learner objects.

library(dplyr)
library(mlr3verse)
df_iris <- iris
df_iris$Petal.Width = df_iris$Petal.Width %>% cut( breaks = c(0,0.5,1,1.5,2,Inf))

task = TaskClassif$new(id = "my_iris", 
                       backend = df_iris, 
                       target = "Species")

train_set = sample(task$nrow, 0.8 * task$nrow)
test_set = setdiff(seq_len(task$nrow), train_set)

task_train = TaskClassif$new(id = "my_iris", 
                       backend = df_iris[train_set,], # use train_set
                       target = "Species")

graph = po("scale", param_vals = list(center = TRUE, scale = TRUE)) %>>%
  po("encode", param_vals = list(method = "one-hot")) %>>%
  mlr_pipeops$get("learner",
                  learner = mlr_learners$get("classif.rpart"))

graph$train(task_train)
graph$pipeops$encode$state$outtasklayout # inspect model input types

graph$pipeops$classif.rpart$predict_type = "prob" 

task_test = TaskClassif$new(id = "my_iris_test",
                       backend = df_iris[test_set,], # use test_set
                       target = "Species")
pred = graph$predict(task_test)
pred$classif.rpart.output$prob

# when you don't have a target variable, just make up one
df_test2 <- df_iris[test_set,]
df_test2$Species = sample(df_iris$Species, length(test_set)) # made-up target

task_test2 = TaskClassif$new(id = "my_iris_test", 
                            backend = df_test2, # use test_set
                            target = "Species")

pred2= graph$predict(task_test2)
pred2$classif.rpart.output$prob
于 2020-10-05T23:25:46.387 回答
0

正如@missuse 所建议的那样,通过使用graph <- preprocess %>>% Learnerand thengraph_learner <- GraphLearner$new(graph)命令,我可以预测 --- predict(TunedLearner, newdata = pred, predict_type="prob")--- 使用 raw data.frame

于 2020-10-06T17:39:35.797 回答