使用欧洲防风草模型预测 R 中的栅格

Using parsnip model to predict a raster in R

我一直在尝试使用 XGBoost 模型在 R 中预测栅格。由于光栅大小,我需要使用 raster::predict()raster::predict(raster, xgboost_model, type="prob")raster::predict(raster, xgboost_model, type="raw") 工作正常。但是,当我尝试使用 raster::predict(raster, xgboost_model, type="class") 预测 classes 时,我得到一个错误:

> predicted<-raster::predict(raster, xgboost_model,  type="class")
Error in v[cells, ] <- predv : incorrect number of subscripts on matrix

这是一个使用 tidymodels 的可重现示例,我用它来训练我的模型。以防万一这是特定于 tidymodel 的。

library(raster)
library(tidymodels)
library(tidyverse)

## Make dummy raster with class as class to predict.
band1<-raster(ncol=10, nrow=10)
values(band1)<-runif(ncell(band1))

band2<-raster(ncol=10, nrow=10)
values(band2)<-runif(ncell(band2))

band3<-raster(ncol=10, nrow=10)
values(band3)<-runif(ncell(band3))

class<-raster(ncol=10, nrow=10)
values(class)<-floor(runif(ncell(class), min=1, max=5))


r<-stack(band1, band2, band3, class)

names(r)<-c("band1", "band2", "band3", "class")

## Convert raster to df for training. 
train<-getValues(r)%>%
  as_tibble()

## Tune and train model.
xgb_spec<-boost_tree(
  trees=50,
  tree_depth = tune(),
  min_n=tune(),
  loss_reduction=tune(),
  sample_size=tune(),
  mtry=tune(),
  learn_rate=tune()
)%>%
  set_engine("xgboost")%>%
  set_mode("classification")

xgb_grid<-grid_latin_hypercube(
  tree_depth(),
  min_n(),
  loss_reduction(),
  sample_size=sample_prop(),
  finalize(mtry(), select(train, -class)),
  learn_rate(),
  size=5
)

xgb_wf<-workflow()%>%
  add_formula(as.factor(class)~band1+band2+band3)%>%
  add_model(xgb_spec)

folds <- vfold_cv(train, v = 5)

xgb_res<-tune_grid(
  xgb_wf,
  resamples=folds,
  grid=xgb_grid,
  control=control_grid(save_pred=T)
)

best_auc<-select_best(xgb_res, "roc_auc")

final_xgb<-finalize_workflow(
  xgb_wf,
  best_auc
)

last_fit<-fit(final_xgb, train)

## remove class layer for test to simulate real world example
test<-r%>%
  dropLayer(4)

## This works
raster::predict(test, last_fit, type="prob")
## This doesn't
raster::predict(test, last_fit, type="class")

type="class" 产生的错误是:

> raster::predict(test, last_fit, type="class")
Error in v[cells, ] <- predv : incorrect number of subscripts on matrix

我用谷歌搜索了我的脸,我弄清楚如何预测 class 的唯一方法是将栅格转换为矩阵,然后将预测添加回栅格。但这真的非常慢。

提前致谢。

啊哈。我想到了。问题在于,当预测类型为 type="class" 时,由 parsnip 包生成的模型总是 returns 小标题。 raster.predict 期望返回一个矩阵。您可以通过向 raster.predict 提供一个函数来解决这个问题,该函数将返回的 parsnip::predicted 模型转换为矩阵。

以下是我如何使用我在问题中创建的原始模型预测栅格:

fun<-function(...){
  p<-predict(...)
  return(as.matrix(as.numeric(p[, 1, drop=T]))) 
}

raster::predict(test, last_fit, type="class", fun=fun)