【问题标题】:Error while running randomForest in R: "Error in y - ymean : non-numeric argument to binary operator"在 R 中运行 randomForest 时出错:“y - ymean 中的错误:二进制运算符的非数字参数”
【发布时间】:2021-09-04 10:38:40
【问题描述】:
birth <- import("smoker_data1.xlsx")


## Splitting the dataset in test and train datasets

mysplit <- sample.split(birth, SplitRatio = 0.65)
train <- subset(birth, mysplit == T)
test <- subset(birth, mysplit == F)

## Build Random Forest model on the test set

mod1 <- randomForest(smoke~., train)

错误消息:错误:y - ymean 中的错误:二元运算符的非数字参数**

【问题讨论】:

  • 现在 mod1

标签: r random-forest decision-tree binary-operators


【解决方案1】:

我认为最好的方法是首先检查烟雾变量的数据类型。 如果可能,尝试使用 as.factor() 更改变量。

library(readxl)
birth <- read_excel("smoker_data1.xlsx")
## Splitting the dataset in test and train datasets
mysplit <- sample.split(birth, SplitRatio = 0.65)
train <- subset(birth, mysplit == T)
test <- subset(birth, mysplit == F)
train$smoke <- as.factor(train$smoke)
## Build Random Forest model on the test set

mod1 <- randomForest(smoke~., train)

你给的数据我已经试过了,只需要在拟合 randomForest 函数之前正确指定数据的类型。

data1$baby_wt <- as.numeric(data1$baby_wt)
data1$income <- as.factor(data1$income)
data1$mother_a <- as.numeric(data1$mother_a)
data1$smoke <- as.factor(data1$smoke)
data1$gestation <- as.numeric(data1$gestation)
data1$mother_wt <- as.numeric(data1$mother_wt)


library(caret)
library(randomForest)
predictors <- names(data1)[!names(data1) %in% "smoke"]
inTrainingSet <- createDataPartition(data1$smoke, p=0.7, list=F)
train<- data1[inTrainingSet,]
test<- data1[-inTrainingSet,]
library(randomForest)
m.rf = randomForest(smoke~., data=train, mtry=sqrt(ncol(x)), ntree=5000,
                    importance=T, proximity=T, probability=T)
m.rf
#############################################
# Test Performance
#############################################
m.pred = predict(m.rf, test[-4], response="class")
m.table <- table(m.pred, test$smoke)
library(caret)
confusionMatrix(m.table)

【讨论】:

  • 我已经拟合了您在 R 中提供的数据。并使用 randomForest 函数运行。似乎没问题..您只需要正确设置数据类型即可。
猜你喜欢
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
相关资源
最近更新 更多