【问题标题】:How to pass a character vector in the train function caret R如何在训练函数 caret R 中传递字符向量
【发布时间】:2016-02-06 14:27:47
【问题描述】:

我想在训练模型时减少变量的数量。我总共有 784 个功能,我想减少到 500 个。我可以使用选择的功能制作一个长字符串,用 + 折叠粘贴命令以获得一个长字符串。 例如,假设这是我的向量

val <- "pixel40+pixel46+pixel48+pixel65+pixel66+pixel67"

然后我想像这样将它传递给 train 函数

Rf_model <- train(label~val, data =training, method="rf", ntree=200, na.action=na.omit)

但我得到了错误

model.frame.default(form = label ~ val, data = training, na.action = na.omit)

谢谢! 路易斯

【问题讨论】:

    标签: r random-forest r-caret


    【解决方案1】:

    你可以这样做:

    val <- "pixel40+pixel46+pixel48+pixel65+pixel66+pixel67"
    
    #use paste to paste the label to val
    #and then use as.formula to convert to formula
    form <- as.formula(paste('label ~', val))
    #> form
    #label ~ pixel40 + pixel46 + pixel48 + pixel65 + pixel66 + pixel67 
    
    Rf_model <- train(form, data =training, method="rf", ntree=200, na.action=na.omit)
    

    此外,在这种情况下,使用字符串创建公式应该没问题,因为这很简单,但对于更复杂的公式,它可能容易出错。在这种情况下,您可以探索stats::update 或Formula 包。


    或者你也可以使用update(虽然我更喜欢以前的方式):

    #> update(label ~ 1,  paste('~', val) )
    #label ~ pixel40 + pixel46 + pixel48 + pixel65 + pixel66 + pixel67
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 2021-01-04
      • 2016-06-24
      • 2016-07-02
      • 1970-01-01
      • 2019-06-27
      • 2013-11-06
      相关资源
      最近更新 更多