栅格预测函数将因子更改为数字并给出错误

如何解决栅格预测函数将因子更改为数字并给出错误

我正在使用 Biomod2 包在 R 中运行一系列物种分布模型。我使用的建模技术之一是使用 rpart 包的分类树分析 (CTA)。

这些模型中的响应是植物物种的存在/不存在,并且预测变量包含在 rasterStack 中。 rasterStack 中的大多数变量都是连续的数值变量,除了一个土地覆盖变量,geology,这是一个因素。我将每个单独的 rasterLayer 堆叠起来,然后使用 as.factor() 将地质层转换为一个因子。

我在尝试从 CTA 进行预测时遇到错误消息。 CTA 模型是用一个数据框构建的,其中“地质”是一个因素(见下文),并在 predict 上使用了栅格 rasterStack 函数(“地质”是一个因素,见下文)。但是,在运行 predict 函数时,我收到一条错误消息,指出我提供的是数字而不是因子。我已经检查了所有可能的点,看看是否以某种方式将“地质”转换回数字,但它似乎是我所看到的任何地方的一个因素(应该如此)。

编辑:更改数据以使其可重现。

library(raster)
library(rpart)

set.seed(123)

# Create sample rasterStack
data.rast <- stack(system.file("external/rlogo.grd",package = "raster"))
# Create one layer as a factor 
data.rast$geology <- as.factor(sampleInt(7,length(data.rast$red),replace = TRUE))

# Create sample presence/absence data by randomly selecting cells of raster
data <- as.data.frame(data.rast)
data <- data[sample(nrow(data),300,replace = FALSE),]
data$pa <- as.factor(sample(0:1,nrow(data),replace = TRUE))
names(data)[4] <- "geology"

head(data)
#     red green blue geology pa
#2463 251   255  255       7  1
#1944 191   190  186       5  0
#5016 162   174  226       7  0
#5771 255   255  253       4  1
#3739 204   205  199       7  0
#5483 131   133  122       3  0

# Build CTA model using presence/absence dataframe
# Parameters set as the defaults in Biomod2 modeling options
cta <- rpart(pa ~ .,data = data,na.action = na.omit,method = "class",control = list(xval = 5,minbucket = 5,minsplit = 5,cp = 0.001,maxdepth = 25))

# Confirm classes of data before running predict function
data.frame(ctaClass = attr(terms(cta),"dataClasses")[2:5],rasterFactor = is.factor(data.rast))
#        ctaClass rasterFactor
#red      numeric        FALSE
#green    numeric        FALSE
#blue     numeric        FALSE
#geology   factor         TRUE

# Once again confirming this rasterLayer is a factor
levels(data.rast$geology)
#[[1]]
#  ID VALUE
#1  1     1
#2  2     2
#3  3     3
#4  4     4
#5  5     5
#6  6     6
#7  7     7

# Run predict function on rasterStack
cta.predict <- predict(object = data.rast,model = cta,type = "class")
#Error: variable 'geology' was fitted with type "factor" but type "numeric" was #supplied
#In addition: Warning message:
#In model.frame.default(Terms,newdata,na.action = na.action,xlev = #attr(object,:
#  variable 'geology' is not a factor

编辑:添加证明它适用于 randomForests 模型

library(randomForest)
rf <- randomForest(pa ~ .,na.action = na.omit)
rf.predict <- predict(data.rast,rf)        

rf.predict
#class      : RasterLayer 
#dimensions : 77,101,7777  (nrow,ncol,ncell)
#resolution : 1,1  (x,y)
#extent     : 0,77  (xmin,xmax,ymin,ymax)
#crs        : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
#source     : memory
#names      : layer 
#values     : 0,1  (min,max)
#attributes :
# ID value
#  1     0
#  2     1

解决方法

在这种情况下,您需要通过提供因子名称和级别来帮助 predict

data$geology <- as.factor(data$geology)
cta.predict <- predict(data.rast,cta,type="class",factors=list(geology=levels(data$geology)))

还要注意 type= 中的 type=class,您不能只执行 class(除非您希望 filenameclass.grd

使用 terra 这会更好一些,我认为(希望)

library(terra)
x <- rast(data.rast*1)
x$geology <- as.factor(x$geology)
cta.predict <- predict(x,type="class")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-