【发布时间】: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
我已经用谷歌搜索了我的脸,我弄清楚如何预测类的唯一方法是将栅格转换为矩阵,然后将预测添加回栅格。但这真的非常非常慢。
提前致谢。
【问题讨论】: