Lesson 3, Topic 1
In Progress

Mapping Slums – Fitting the Model

This lecture starts with a short reconsideration of what happened in the last view steps. The aim of this lecture is to fit your model into the process of calculating a final outcome. Therefore you will have to apply the previously exported data from the random forrest model and the raster stack you’ve just created and combine them. You’ll learn how to to import the neceessary data into R-Studio to finally calculate an output that shows the prediction of slum settlement in our study area of Lagos. Also for a faster processing you will be taught how you can split the stack into blocks sizes.

At the end of the lecture you will be able to visualize your result in R-Studio but for a better visualization you will learn how to edit it in Q-GIS as well- which will be the final step of this mini – MOOC.

You can find the code which is used for this topic below.

YouTube

By loading the video, you agree to YouTube’s privacy policy.
Learn more

Load video

Code used in this topic
######################Fit Random forest###############

######### INITAL PARAMETERS ############

#inputs
input_model <- "Result_mooc/RF_model.rds"
input_stack <- "Result_mooc/Image_stack.tif"


#others
number_cores <- 6


########## PREPARE DATA ############

#####read stack
sta.vars <- stack(input_stack)

######read model
log.mod <- readRDS(input_model)

####Visualize data#####
varImpPlot(log.mod)
log.mod$importance
print(sta.vars)
plot(sta.vars)

#######add names
log.vars <- rownames(log.mod$importance)
names(sta.vars) <- log.vars

######split stack into block for faster processing
img.blocks <- blockSize(sta.vars)

######temp data
csv.fol <- paste0(output_folder,"/csv");dir.create(csv.fol,showWarnings=F)

########## PROCESSING... ############

#turn on cores to run parallel each  bricks
detectCores()
cl<-makeCluster(number_cores)
registerDoParallel(cl)


#start parallel
foreach(i=1:img.blocks$n,.packages=c("raster","randomForest")) %dopar% {
  #get data
  data.input <- as.data.frame(getValues(sta.vars,row=img.blocks$row[i],nrows=img.blocks$nrows[i]))
  #apply model
  data.input <- predict(log.mod,data.input,type = "prob")
  data.input <- data.input[,2]
  #save outputs
  output.name <- paste0(csv.fol,'/pred_',i,'.csv')
  write.csv(data.input,output.name)
}
stopCluster(cl)



########## READ AND JOIN ############
#get the csv data
csv.files <- mixedsort(list.files(csv.fol,full.names=T,pattern=".csv"))
csv.values <- lapply(csv.files,function(x){
  x.val <- read.csv(x)[,2]
  return(x.val)
})
#add to raster
template <- sta.vars[[1]]
values(template) <- unlist(csv.values)
names(template) <- "prediction"

####Visulae predicted map######
plot(template)


#save
output.name <- paste0(output_folder,"/prediction_RF.tif")
writeRaster(template,output.name,overwrite=TRUE)