我正在尝试创建一个栅格,以显示随机森林预测和神经网络预测在哪里达成共识和不同意。每个栅格都是对6个土地类别的预测,我想创建一个新的栅格,以比较两者之间的比较:同意的预测像元为绿色,而不同意的预测像元为红色。
这是我的两种预测方法及其栅格的代码:
trainD <- dataAll[dataAll$sampleType == "train",]
validD <- dataAll[dataAll$sampleType == "valid",]
# Random Forest
# use 'Caret' package to find the optimal parameter settings
tc <- trainControl(method = "repeatedcv",
number = 10, # number 10 fold
repeats = 10) # number of repeats
rf.grid <- expand.grid(mtry=1:sqrt(9)) # use 9 bc we have 9 bands
# train the random forest model to the Sentinel-2 data through Caret
trainD <- na.omit(trainD) #omit points in cloud areas from training points
rf_model <- caret::train(x = trainD[,c(5:13)], #digital number data
y = as.factor(trainD$landcID),
method = "rf",
metric="Accuracy",
trainControl = tc, #use parameter tuning
tuneGrid = rf.grid) #parameter tuning grid
#check output
rf_model
# Change name in raster stack to match training data
names(allbandsCloudf) <- c("B2","B3","B4","B5","B6","B7","B8","B11","B12")
# Apply the random forest model to the Sentinel-2 data
rf_prediction <- raster::predict(allbandsCloudf, model=rf_model)
#view predictions
plot(rf_prediction)
# landcover class names
landclass
# set up categorical colors for each class using hex codes
landclass$cols <-c("#a6d854","#8da0cb","#66c2a5",
"#fc8d62","#ffffb3","#ffd92f")
# make plot and hide legend
plot(rf_prediction, #random forest prediction
breaks=seq(0,6), #number of landclasses
col=landclass$cols ,
legend=FALSE, axes=FALSE) #hide legend
# Neural Networks
# set up grid
nnet.grid <- expand.grid(size = seq(from = 16, to = 28, by = 2),
decay = seq(from = 0.1, to = 0.6, by = 0.1))
# train the model
nnet_model <- caret::train(x = trainD[,c(5:13)],
y = as.factor(trainD$landcID),
method = "nnet",
metric= "Accuracy",
trainControl = tc,
tuneGrid = nnet.grid,
trace=FALSE)
# view the training summary
nnet_model
# apply the neural network model to the Sentinel-2 data
nnet_prediction <- raster::predict(allbandsCloudf, model=nnet_model)
# make plot and hide legend
plot(nnet_prediction, #plot the neural network predictions
breaks=seq(0,6), #number of landclasses
col=landclass$cols ,
legend=FALSE) #hide the legend
答案 0 :(得分:0)
我能够找出自己的问题的答案!我只是使用了叠加层,然后将颜色设置为想要的颜色并添加了图例。
如果有人试图解决类似的问题,请使用以下代码:
diff <- overlay(rf_prediction, nnet_prediction, fun=function(a,b) return(a==b))
plot(diff,
col=c('#FFE4E1','#228B22'),
legend=FALSE,
axes=FALSE)
legend("left", legend=c("Agree", "Disagree"),
col=c("#228B22", "#FFE4E1"), pch = 15, cex=0.8)