我尝试在 randomForests 的大型 1027206000 单元格栅格上预测森林林分类型(n = 43 个类别,编码地形、地质、水和养分供应等)。
在我用作协变量的许多 DEM 派生参数中,我还有 2 个栅格,其 ID 编号为地质图和土壤图。许多分类映射单元都带有这些 ID。我用数据框训练模型,并通过“合并”将分类映射单元附加到它。
到目前为止一切正常。该模型做了它应该做的事情,我也可以预测数据框中保存的一些测试数据。
但现在我打算制作一些预测地图。但是当使用光栅堆栈或砖运行模型时,只会给出所有 NA 的光栅。我的印象是,我在将因子级别传递给 rasterstack/rasterbrick 时做错了。
她是一些重现问题的代码。
library(raster)
library(rasterVis)
library(randomForest)
# make a raster
set.seed(0)
r <- raster(nrow=10, ncol=10)
r[] <- runif(ncell(r)) * 10
is.factor(r)
r <- round(r)
# make faktor
f <- as.factor(r)
is.factor(f)
# get some none-sense levels
x <- levels(f)[[1]]
x$code <- paste("A",letters[10:20])
x$code2 <- paste("B",letters[10:20])
x$code3 <- letters[10:20]
levels(f) <- x
f<-deratify(f) # make a brick
levels(f)
set.seed(2)
# get some none-sense dataframe
xx<-data.frame(code=sample(rep(paste("A",letters[10:20]),10)),
code2=sample(rep(paste("B",letters[10:20]),10)),
code3=rep( letters[10:20],10),
y=as.factor(sample(rep(paste(rep(1:5)),22))))
# fit and predict a random forest with it
ranfor<-randomForest(y~.,data=xx,ntree=100)
predict(ranfor)
# try to predict with a raster
names(f)<-c("code","code2","code3")
a<-predict(object=f,ranfor,na.omit=T,factors=list(code=levels(xx$code),
code2=levels(xx$code2),
code3=levels(xx$code3)))
plot(a) # gives an empty raster
# convert the raster to a dataframe and predict again
x<-as.data.frame(f)
names(x)<-c("code","code2","code3")
aa<-predict(ranfor,x)
plot(aa) # works just fine!
有什么建议么?谢谢!
R version 3.1.2 (2014-10-31) Platform: x86_64-w64-mingw32/x64 (64-bit)
locale: [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages: [1] stats graphics grDevices utils datasets methods base
other attached packages: [1] randomForest_4.6-10 rasterVis_0.35 latticeExtra_0.6-26 RColorBrewer_1.1-2 lattice_0.20-33 raster_2.4-15 sp_1.1-1
loaded via a namespace (and not attached): [1] grid_3.1.2 hexbin_1.27.0 Rcpp_0.11.6 rgdal_1.0-4 tools_3.1.2 zoo_1.7-12