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

问题描述

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

> predicted<-raster::predict(raster,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,type="class")

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

> raster::predict(test,] <- predv : incorrect number of subscripts on matrix

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

提前致谢。

解决方法

啊哈。我想到了。问题是当预测类型为 type="class" 时,由 raster.predict 包生成的模型总是返回一个 tibble。 raster.predict 期望返回一个矩阵。您可以通过向 parsnip::predict 提供一个函数来解决这个问题,该函数将返回的 fun<-function(...){ p<-predict(...) return(as.matrix(as.numeric(p[,1,drop=T]))) } raster::predict(test,last_fit,type="class",fun=fun) ed 模型转换为矩阵。

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

import numpy as np
import cv2


img = cv2.imread('image1.jpg')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

img_w_treshold = cv2.threshold(img,150,255,cv2.ADAPTIVE_THRESH_MEAN_C)[1]
cv2.imshow('img_w_treshold',img_w_treshold)
cv2.waitKey()

blured_image = cv2.GaussianBlur(img_w_treshold,(99,99),0)
cv2.imshow('blured_image',blured_image)
cv2.waitKey()