Image classification (raster stack) with random forest (package ranger)
You can run predictions from a ranger model on a raster stack by training the model within the train function of the caret package:
library(caret)
ranger.model<-train(Species ~ ., data=iris,method = "ranger")
ranger.pred<-predict(r,ranger.model)
However, this doesn't work if you want to predict the standard error, as the prediction function for train objects does not accept type = 'se'
. I got around this by building a function for the purpose using this document:
https://cran.r-project.org/web/packages/raster/vignettes/functions.pdf
# Function to predict standard errors on a raster
predfun <- function(x, model, type, filename)
{
out <- raster(x)
bs <- blockSize(out)
out <- writeStart(out, filename, overwrite=TRUE)
for (i in 1:bs$n) {
v <- getValues(x, row=bs$row[i], nrows=bs$nrows[i])
nas<-apply(v,1,function(x) sum(is.na(x)))
p<-numeric(length = nrow(v))
p[nas > 0]<-NA
p[nas == 0]<-predict(object = model,
v[nas == 0,],
type = 'se')$se
out <- writeValues(out, p, bs$row[i])
}
out <- writeStop(out)
return(out)
}
# New ranger model
ranger.model<-ranger(Species ~ .
, data=iris
, probability=TRUE
, keep.inbag=TRUE
)
# Run predictions
se<-predfun(r
, model = ranger.model
, type = "se"
, filename = paste0(getwd(),"/se.tif")
)
After a bit of fiddling:
pacman::p_load(raster, nnet, ranger)
data(iris)
# put iris data into raster
r<-list()
for(i in 1:4){
r[[i]]<-raster(nrows=10, ncols=15)
r[[i]][]<-iris[,i]
}
r<-stack(r)
names(r)<-names(iris)[1:4]
# multinom (an example that works)
nn.model <- multinom(Species ~ ., data=iris, trace=F)
nn.pred <- predict(r,nn.model) # predict(object, newdata, type = c("raw","class"), ...)
# ranger (doesn't work)
ranger.model <- ranger(Species ~ ., data=iris)
ranger.pred <- predict(ranger.model, as.data.frame(as.matrix(r)))
as.data.frame(as.matrix(r))
did it!
Disclaimer: I did not check the output for correctness, so this might produce no results at all, but...
identical(iris$Species, ranger.pred$predictions)
It worked for me with randomForest instead of ranger if that helps
library(randomForest)
rf.model<-randomForest(Species ~ ., data=iris)
rf.pred<-predict(r,rf.model)