4

Could anyone point me to a Random Forest tutorial for predicting a spatial random variable? Or an easy dataset to try to work through.

For Decision Trees and Random Forests, I found some very good tutorials from Trevor Stephens, Kaggle, and Datacamp, here, here, and here. But I'd like to look at a spatial example - I've come across a lot of literature on this subject but nothing as clear cut as the above links. The closest thing perhaps would be Jeffrey Evan's code here, but it appears to be unfinished.

2

Here is an example using R and a hyperspectral AVIRIS image of the Kennedy Space Centre which is provided for testing spatial classifications.

## required packages for spatial data random forest analysis
require(raster) 
require(rgdal)
install.packages("randomForest")
require(randomForest)

## download the aviris data
download.file("http://www.csr.utexas.edu/hyperspectral/data/KSC/KSC_data.bin", "KSC_data.bin")
download.file("http://www.csr.utexas.edu/hyperspectral/data/KSC/KSC_data.bin.hdr", "KSC_data.bin.hdr")

## download the ground truth data
download.file("http://www.csr.utexas.edu/hyperspectral/data/KSC/KSC_classes.bin", "KSC_classes.bin")
download.file("http://www.csr.utexas.edu/hyperspectral/data/KSC/KSC_classes.bin.hdr", "KSC_classes.bin.hdr")

bild <- stack("KSC_data.bin") #create raster stack

## plot to see what you are working with
plotRGB(bild, 25, 15, 5, stretch="lin") #true color composite
plotRGB(bild, 40, 25, 15, stretch="lin") #NIR/R/G-false color composite

classes <- stack("KSC_classes.bin") #import the ground truth data
gt <- rasterToPolygons(classes)

gt.class <- as.factor(t(gt@data)) #read class labels

gt.ref <- extract(bild, gt) #read reflectance values from image

## Random Forest classification
rfmod <- randomForest(gt.ref, gt.class) #create rf model

map <- predict(bild, rfmod) #predict classes with rf model

cl <- colorRampPalette(colors()[c (81, 152, 142, 493, 24, 652, 620, 254, 102, 624, 417, 498, 26)]) #one color per class

plot(map, col=cl(13), legend=F) #plot the result of the classification

writeRaster(map, "KSC_RandomForest.tif", format="GTiff") #export of the classified image

Source: This example is adapted from a lecture by Hannes Feilhauer and can also be found in the FAU GISwiki (in German).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.