我正在使用train
函数训练一个neuralnet
模型,并使用recipes
包对数据进行预处理。
有没有什么函数可以从模型中进行预测,然后将这些预测值重新缩放到它们原始的范围内,在我的例子中是[1, 100]
?
library(caret)library(recipes)library(neuralnet)# 创建数据集 - 乘法表 tt <- data.frame(multiplier = rep(1:10, times = 10), multiplicand = rep(1:10, each = 10))tt <- cbind(tt, data.frame(product = tt$multiplier * tt$multiplicand))# 分割数据 indexes <- createDataPartition(tt$product, times = 1, p = 0.7, list = FALSE)tt.train <- tt[indexes,]tt.test <- tt[-indexes,]# 预处理数据的配方 rec_reg <- recipe(product ~ ., data = tt.train) %>% step_center(all_predictors()) %>% step_scale(all_outcomes()) %>% step_center(all_outcomes()) %>% step_scale(all_predictors())# 训练 train.control <- trainControl(method = "repeatedcv", number = 10, repeats = 3, savePredictions = TRUE)tune.grid <- expand.grid(layer1 = 8, layer2 = 0, layer3 = 0)# 设置种子以确保结果可重复 set.seed(12)tt.cv <- train(rec_reg, data = tt.train, method = 'neuralnet', tuneGrid = tune.grid, trControl = train.control, algorithm = 'backprop', learningrate = 0.005, lifesign = 'minimal')
回答:
如果你使用step_normalize
代替step_scale
和step_center
,你可以使用以下函数基于recipe
来“反标准化”。(如果你更喜欢使用两步进行标准化,你需要调整unnormalize
函数。)
这个函数用于提取相关的步骤。
#' 提取步骤项目#'#' 从预处理的配方中返回提取的步骤项目。#'#' @param recipe 预处理的配方对象。#' @param step 预处理配方中的步骤。#' @param item 预处理配方中的项目。#' @param enframe 步骤项目是否需要框架化?#'#' @exportextract_step_item <- function(recipe, step, item, enframe = TRUE) { d <- recipe$steps[[which(purrr::map_chr(recipe$steps, ~ class(.)[1]) == step)]][[item]] if (enframe) { tibble::enframe(d) %>% tidyr::spread(key = 1, value = 2) } else { d }}
这个函数用于进行反标准化。因此,它会乘以标准差并加上均值。
#' 反标准化变量#'#' 使用配方对象中的标准差和均值对变量进行反标准化。参见 \code{?recipes}。#'#' @param x 要反标准化的数值向量。#' @param rec 配方对象。#' @param var 配方对象中的变量名。#'#' @exportunnormalize <- function(x, rec, var) { var_sd <- extract_step_item(rec, "step_normalize", "sds") %>% dplyr::pull(var) var_mean <- extract_step_item(rec, "step_normalize", "means") %>% dplyr::pull(var) (x * var_sd) + var_mean}
所以你应该能够生成预测,然后使用:
unnormalize(predictions, prepped_recipe_obj, outcome_var_name)
其中predictions
是训练模型生成的预测值向量,prepped_recipe_obj
在你的例子中是rec_reg
,outcome_var_name
在你的例子中是product
。