r - R中这行代码的错误可能是什么?
问题描述
fit <- randomForest(class~. ,data = train_data)
谁能告诉我这行代码有什么问题?
这里的 train_data 是预测收入为 >50k 或 <50k 的训练数据,我在这一行中得到的错误是:
y - ymean 中的错误:二元运算符的非数字参数此外:警告消息:1:在 randomForest.default(m, y, ...) 中:
响应具有五个或更少的唯一值。您确定要进行回归吗?2:在 mean.default(y) 中:参数不是数字或逻辑:返回 NA
解决方案
似乎您正在尝试对字符因变量进行分类。假设我们使用来自 kaggle的这个奇妙的数据集:
library(randomForest)
train_data = read.csv("credit_train.csv",stringsAsFactors=FALSE)
str(train_data)
'data.frame': 808 obs. of 17 variables:
$ Class : chr "Good" "Bad" "Good" "Good" ...
$ Duration : int 6 48 12 36 24 12 30 48 12 24 ...
$ Amount : int 1169 5951 2096 9055 2835 3059 5234 4308 1567 1199 ...
$ InstallmentRatePercentage : int 4 2 2 2 3 2 4 3 1 4 ...
$ ResidenceDuration : int 4 2 3 4 4 4 2 4 1 4 ...
$ Age : int 67 22 49 35 53 61 28 24 22 60 ...
$ NumberExistingCredits : int 2 1 1 1 1 1 2 1 1 2 ...
$ NumberPeopleMaintenance : int 1 1 2 2 1 1 1 1 1 1 ...
$ Telephone : int 0 1 1 0 1 1 1 1 0 1 ...
$ ForeignWorker : int 1 1 1 1 1 1 1 1 1 1 ...
$ CheckingAccountStatus.lt.0 : int 1 0 0 0 0 0 0 1 0 1 ...
$ CheckingAccountStatus.0.to.200: int 0 1 0 0 0 0 1 0 1 0 ...
$ CheckingAccountStatus.gt.200 : int 0 0 0 0 0 0 0 0 0 0 ...
$ CreditHistory.ThisBank.AllPaid: int 0 0 0 0 0 0 0 0 0 0 ...
$ CreditHistory.PaidDuly : int 0 1 0 1 1 1 0 1 1 0 ...
$ CreditHistory.Delay : int 0 0 0 0 0 0 0 0 0 0 ...
$ CreditHistory.Critical : int 1 0 1 0 0 0 1 0 0 1 ...
fit <- randomForest(Class~. ,data = train_data)
Error in y - ymean : non-numeric argument to binary operator
In addition: Warning messages:
1: In randomForest.default(m, y, ...) :
The response has five or fewer unique values. Are you sure you want to do regression?
2: In mean.default(y) : argument is not numeric or logical: returning NA
你可以看到我得到了同样的错误。你的因变量是一个字符。我们将其转换为一个因子并且它可以工作:
train_data$Class = factor(train_data$Class)
fit <- randomForest(Class~. ,data = train_data)
推荐阅读
- javascript - 状态已充满对象但无法访问作为回报
- json - 从 unix 日志文件中提取数据,构造 JSON 并使用 curl 执行 post 请求
- python - 下载 Kaggle 数据集
- python - 来自多个数据框的pairplot列,由类别列中的类标记
- r - 循环读取多个大文件
- office365 - 无法从 Desktop Excel 365 (Windows) 的对话框中的单元格中插入字符串
- ios - 在 swiftUI 中显示来自多个选项的工作表
- java - 解决maven中的依赖冲突
- javascript - JavaScript 通知和 Service Worker API:为什么注册后 serviceWorker.ready 承诺?
- android - Android:无法转换为 java.lang.CharSequence