【问题标题】:Caret train function for muliple data frames as function多个数据帧的插入符号训练函数作为函数
【发布时间】:2022-01-14 19:43:02
【问题描述】:

在 6 年前就有一个与我类似的问题,但尚未解决 (R -- Can I apply the train function in caret to a list of data frames?) 这就是我再次提出这个话题的原因。

我现在正在为我的大型 R 项目编写自己的函数,我想知道是否有机会总结包 caret 的模型训练函数 train() 用于具有不同预测变量的不同数据帧. 我的函数应该是这样的:

lda_ex <- function(data, predictor){
   model <- train(predictor ~., data,
      method = "lda",
      trControl = trainControl(method = "none"),
      preProc = c("center","scale"))
   return(model)
}

之后使用它应该是这样的:

data_iris <- iris
predictor_iris <- "Species"

iris_res <- lda_ex(data = data_iris, predictor = predictor_iris)

不幸的是,就我而言,R 公式无法处理作为输入的变量。

我有什么遗漏吗? 提前感谢您帮助我!

解决这个问题对我保持功能表清洁和安全工作有很大帮助。

【问题讨论】:

    标签: r function r-caret caret


    【解决方案1】:

    通过编写predictor_iris &lt;- "Species",您基本上是在predictor_iris 中保存了一个字符串对象。因此,当您运行lda_ex 时,我猜您会遇到一些与train() 中的formula 对象有关的错误,因为您正在尝试使用协变量向量来预测字符串。

    确实,我尝试了以下玩具示例:

    X = rnorm(1000)
    Y = runif(1000)
    
    predictor = "Y"
    
    lm(predictor ~ X)
    

    这给出了关于变量长度差异的错误。

    让我修改你的函数:

    lda_ex <- function(data, formula){
      model <- train(formula, data,
                     method = "lda",
                     trControl = trainControl(method = "none"),
                     preProc = c("center","scale"))
      return(model)
    }
    

    关键区别在于,现在我们必须传入整个 formula,而不仅仅是预测变量。这样,我们就避免了字符串相关的问题。

    library(caret) # Recall to specify the packages needed to reproduce your examples!
    
    data_iris <- iris
    formula_iris = Species ~ . # Key difference!
    iris_res <- lda_ex(data = data_iris, formula = formula_iris)
    

    【讨论】:

    • 不幸的是,它给出了与您提供的修改相同的变量长度差异错误
    • Ops,我的回答有误。我要编辑它。
    • 非常感谢!!!有用!太兴奋了 :)!
    • 我很高兴听到这个消息 :) 如果您觉得您的问题已解决,请考虑支持并接受我的问题 :)
    猜你喜欢
    • 2019-09-06
    • 2021-01-22
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2012-01-16
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多