我有一个使用caret软件包训练的随机森林模型,该软件包包含数字和分类预测因子。我试图使用这个经过训练的模型对一个新的数据集进行预测,该数据集是一个光栅堆栈,每个预测值包含一层。我已使用
ratify
中的函数
raster
包,以及通过添加光栅属性表(RAT)来添加与训练集语法相对应的字符串,但当我预测时,会出现以下错误:
# Error in predict.randomForest(modelFit, newdata) :
# Type of predictors in new data do not match that of the training data.
我想我可能在某种程度上误解了RAT,或者我误解了RAT的功能。下面是一个最小的可复制示例。有什么想法吗?
require(caret)
require(raster)
set.seed(150)
data("iris")
# Training dataset
iris.x<-iris[,1:4]
iris.x$Cat<-"Low"
iris.x$Cat[1:60]<-"High"
iris.x$Cat<-as.factor(as.character(iris.x$Cat))
iris.y<-iris$Species
# Train RF model in Caret
ctrl<-trainControl("cv", num=5, p = 0.9)
mod<- train(iris.x,iris.y,
method="rf",
trControl=trainControl(method = "cv"))
# Create raster stack prediction dataset
r <- raster(ncol=10, nrow=5)
tt <- sapply(1:4, function(x) setValues(r, round(runif(ncell(r),1,5))))
#Categorical raster layer with RAT
r_cat<-raster(ncol=10, nrow=5)
r_cat[1:25]<-1
r_cat[26:50]<-2
ratr_cat <- ratify(r_cat)
rat <- levels(ratr_cat)[[1]]
rat$PCN <- c(1,2)
rat$PCN_level <- c('Low','High')
levels(ratr_cat) <- rat
#Stack raster layers
t.stack <- stack(c(tt,ratr_cat),RAT = TRUE)
#Make sure names in stack match training dataset
names(t.stack)<-c('Sepal.Length','Sepal.Width', 'Petal.Length', 'Petal.Width','Cat')
#Ensure that categorical layer still has RAT and is a factor
t.stack[['Cat']] #yep
is.factor(t.stack[['Cat']]) #yep
#Predict new data using model
mod_pred <- predict(t.stack, mod)