Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
randomForest[R]是否不接受逻辑变量作为响应,而是接受它作为预测?_R_Random Forest - Fatal编程技术网

randomForest[R]是否不接受逻辑变量作为响应,而是接受它作为预测?

randomForest[R]是否不接受逻辑变量作为响应,而是接受它作为预测?,r,random-forest,R,Random Forest,嗨,我在R中使用了randomForest,它不接受逻辑变量作为响应(Y),但似乎接受它作为预测器(X)。我有点惊讶b/c我认为逻辑基本上是两级因素 我的问题是:randomForest接受逻辑作为预测,而不是作为响应,这是真的吗?为什么是这样? 其他通用模型(glmnet、svm等)是否接受逻辑变量 欢迎任何解释/讨论。谢谢 N = 100 data1 = data.frame(age = sample(1:80, N, replace=T), sex

嗨,我在R中使用了randomForest,它不接受逻辑变量作为响应(Y),但似乎接受它作为预测器(X)。我有点惊讶b/c我认为逻辑基本上是两级因素

我的问题是:randomForest接受逻辑作为预测,而不是作为响应,这是真的吗?为什么是这样? 其他通用模型(glmnet、svm等)是否接受逻辑变量

欢迎任何解释/讨论。谢谢

N = 100

data1 = data.frame(age = sample(1:80, N, replace=T),
                   sex = sample(c('M', 'F'), N, replace=T),
                   veteran = sample(c(T, F), N, replace=T),
                   exercise = sample(c(T, F), N, replace=T))

sapply(data1, class)
#       age       sex   veteran  exercise 
# "integer"  "factor" "logical" "logical" 

# this doesnt work b/c exercise is logical
rf = randomForest(exercise ~ ., data = data1, importance = T)
# Warning message:
#         In randomForest.default(m, y, ...) :
#         The response has five or fewer unique values.  Are you sure you want to do regression?

# this works, and veteran and exercise (logical) work as predictors
rf = randomForest(sex ~ ., data = data1, importance = T)
importance(rf)
#                   F         M MeanDecreaseAccuracy MeanDecreaseGini
# age      -2.0214486 -7.584637            -6.242150         6.956147
# veteran   4.6509542  3.168551             4.605862         1.846428
# exercise -0.1205806 -6.226174            -3.924871         1.013030

# convert it to factor and it works
rf = randomForest(as.factor(exercise) ~ ., data = data1, importance = T)

这种行为的原因是randomForest还能够进行回归(除了分类)。您还可以在获得的警告消息中观察到:

响应具有五个或更少的唯一值。您确定要执行回归吗

该函数根据给定响应向量的类型决定回归和分类。如果是因子分类,则进行回归(这是有意义的,因为回归响应向量永远不会是因子/分类变量)

关于您的问题:在输入数据集中使用逻辑变量(预测器)没有问题,randomForest能够像您所期望的那样完美地处理这一问题

training_data <- data.frame(x = rep(c(T,F), times = 1000)) # training data with logical
response <- as.factor(rep(c(F,T), times = 1000)) # inverse of training data
randomForest(response ~ ., data = training_data) # returns 100% accurate classifier

training\u数据感谢@Gerd Marvin-猜猜他们为什么不在源代码中包含这种强制(逻辑到因子)?感谢@Gerd Marvin的讨论。您提到“如果您的逻辑响应向量只包含TRUE或FALSE值,那么您可能会遇到问题。”--但因子变量只能有一个值…@YZhang您是对的。我把它混在一起了,因为我曾经遇到过一个问题,当我强迫我的训练数据使用不完整等级的因子。。。