如何在训练函数插入符号 R 中传递字符向量 [英] How to pass a character vector in the train function caret R

查看:31
本文介绍了如何在训练函数插入符号 R 中传递字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在训练模型时减少变量的数量.我总共有 784 个特征,我想减少到 500 个.我可以用选定的特征制作一个长字符串,使用粘贴命令折叠成一个长字符串.例如,假设这是我的向量

I want to reduce the number of variables when i train my model. I have a total of 784 features that I want to reduce to lets say 500. I can make a long string with the selected featuees with the Paste command collapsed with + to have a long string. For example, lets say this is my vector

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

然后我想像这样将它传递给火车功能

then I would like to pass it to the train function like so

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)

谢谢!路易斯

推荐答案

你可以这样做:

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::updateFormula 包.

Also, in this case using a string to create a formula should be fine since this is straightforward, but for more complex formulas it might prove error prone. In such cases you can explore stats::update or the Formula package.

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

Or you could alternatively use update (although I prefer the previous way):

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

这篇关于如何在训练函数插入符号 R 中传递字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆