2012-01-24 29 views
4

我似乎无法得到adabagbaggingpredict.bagging工作。设置装订在R adabag

predict.bagging手册页,有以下几点:

library(adabag) 
library(rpart) 
data(iris) 
names(iris)<-c("LS","AS","LP","AP","Especies") 
sub <- c(sample(1:50, 25), sample(51:100, 25), sample(101:150, 25)) 
iris.bagging <- bagging(Especies ~ ., data=iris[sub,], mfinal=10) 
iris.predbagging<- predict.bagging(iris.bagging, newdata=iris[-sub,]) 
iris.predbagging 

这是好的和工作。但是,当我稍微更改predict.bagging中的newdata时,它停止工作。

主要是,我不能真正删除或更改Especies列,这很奇怪,因为那是我应该预测的那一列!一个例子。

testdata <- iris[-sub, ] 
result <- predict.bagging(iris.bagging, newdata=testdata) 

....这工作正常,几乎是副本的例子。然而,这将产生一个错误

testdata <- iris[-sub, -5] #this deletes the Especies column! 
result <- predict.bagging(iris.bagging, newdata=testdata) 

而且这个

testdata <- iris[-sub, ] 
testdata$Especies <- c("virginica") #sets up everything as virginica 
result <- predict.bagging(iris.bagging, newdata=testdata) 

产生一个错误!

这是怎么回事?我想用bagging来制作一个分类器,但是我不能提前知道结果,这就打破了这个观点。

编辑:好吧,它会变得很好。

> testdata <- iris[150,] 
> predict.bagging(iris.bagging, newdata=testdata) #all working 
> testdata 
    LS AS LP AP Especies 
150 5.9 3 5.1 1.8 virginica 
> is(testdata) 
[1] "data.frame" "list"  "oldClass" "vector"  
> testdata$Especies = "virginica" 
> testdata 
    LS AS LP AP Especies 
150 5.9 3 5.1 1.8 virginica #!!!the same thing!!! 
> is(testdata) 
[1] "data.frame" "list"  "oldClass" "vector" #the same object type!!! 
> 
> predict.bagging(iris.bagging, newdata = testdata) 
Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr, : 
    length of 'dimnames' [2] not equal to array extent 
In addition: Warning messages: 
1: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
2: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
3: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
4: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
5: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
6: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
7: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
8: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
9: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
10: In is.na(e2) : is.na() applied to non-(list or vector) of type 'NULL' 
> 

回答

3

哦,我知道了,有点。

显然,在最后的Especies列中,是一个因子,而不是字符串的向量。因此,为了改变它,我有因式分解这样的:

testdata$Especies <- factor(c("virginica"), levels=c("setosa", "versicolor", "virginica"))

如果我有没有最后一列的数据帧,我不得不反正它添加和因子的水平必须完全像原始表格的因素一样,实际内容是无关紧要的。

我不接受我的答案,因为目前为止,因为有人可以更好地解释原因。

+1

我还是不明白为什么会这样,但我很高兴其他人也有这个问题。通常,预测函数只需要新的输入数据而不是响应。 – Max

+0

因此,创建虚拟响应变量行并将其解释为一个“因素”有诀窍吗? –

+0

我近两年没有碰过R(幸运的是!!),所以我现在不能说真的:( –