【问题标题】:Using parsnip model to predict a raster in R使用欧洲防风草模型预测 R 中的栅格
【发布时间】:2021-03-31 04:09:26
【问题描述】:

我一直在尝试使用 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") 来预测类时,我得到一个错误:

> 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

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

提前致谢。

【问题讨论】:

    标签: r xgboost r-raster


    【解决方案1】:

    啊哈。我想到了。问题是当预测类型为type="class" 时,parsnip 包生成的模型总是返回一个 tibble。 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)
    

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2020-08-19
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多