首页 > 解决方案 > Error in Random Forest implementation using R

问题描述

I am still a beginner in ML algorithms. I was trying to apply Random Forest on a dataset but I faced an error while trying to fit the model. Below is the error

rf <- randomForest(winequality.red$quality ~ ., data=train)

Error in model.frame.default(formula = winequality.red$quality ~ ., data = train, : variable lengths differ (found for 'fixed.acidity')

I can send the data set and code if needed. thanks in advance for any hints. Best Mohammed

标签: rrandom-forest

解决方案


看看公式界面

data您一起指定您正在使用的数据集。然后你给出一个formula你可以指定的地方,哪些变量是独立的/依赖的,或者你怎么称呼它们。

你的公式可能应该是

rf <- randomForest(quality ~ ., data=winequality.red)

这意味着,您正在使用数据集winequality.red。从这个数据集中,您想要构建一个预测quality. (波浪号)之前的变量~始终是您想要预测的(因变量)。波浪号.之后的基本意思是,您想使用数据集的所有其他变量来构建预测模型。因此,在~您指定自变量之后。依赖/独立的名称可能会有很大差异......基于上下文(例如预测/预测,......)

这是一个经典的例子:

iris.rf <- randomForest(Species ~ ., data=iris)

你有 iris 数据集,一个带有花朵测量值的数据集。

 $ Sepal.Length: num 
 $ Sepal.Width : num  
 $ Petal.Length: num  
 $ Petal.Width : num  
 $ Species     : Factor w/ 3 levels "setosa","versicolor"

你想建立一个模型来预测一朵花属于哪个类别/哪个物种。在上面的代码中,您说data=iris将 while 数据集提供给函数。然后您指定formula模型的外观。在这种情况下,我们要预测 Species,所以我们Species在 the 之前~加上.波浪号之后我们说,应该使用Sepal.Length, Sepal.Width, , 来预测。Petal.LengthPetal.WidthSpecies

但是我们没有像iris$Species在 中那样引用它们formula,因为函数已经知道它应该在哪个数据集上查找变量。


推荐阅读