【问题标题】:Passing levels to predict randomForest with a raster传递级别以使用栅格预测 randomForest
【发布时间】:2015-10-07 05:57:14
【问题描述】:

我尝试预测林分类型(n=43 类编码 地形、地质、水和养分供应等) 在 randomForests 的 1027206000 大型像元栅格上。

在我用作协变量的许多 DEM 派生参数中,我还有 2 个带有 ID 号的栅格,分别是地质图和土壤图。许多分类映射单元都带有这些 ID。我使用数据框训练模型,并通过“合并”将分类映射单元附加到它。

到目前为止一切正常。模型做了它应该做的,我 也可以预测数据框中的一些测试数据。

但现在我打算制作一些预测地图。 但是当使用 rasterstack 或砖块运行模型时 只给出所有 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

【问题讨论】:

    标签: r geospatial random-forest r-raster


    【解决方案1】:

    为了解决这些问题,在将因子级别从字符串重新编码为“数字”级别后,我创建了所有分类变量的栅格。然后 predict:raster 完成这项工作。然而,这是一个非常糟糕的问题解决方案。仍然如此:非常感谢任何帮助!

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 2017-01-11
      • 2018-05-11
      相关资源
      最近更新 更多