You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何并行运行dredge函数?遇“no nobs method”错误求解决

解决dredge并行运行时的no 'nobs' method is available错误

你在使用MuMIn包的dredge函数并行处理多变量模型时遇到报错,可复现代码如下:

library(palmerpenguins)
library(MuMIn)
library(dplyr)

# 创建并清理数据集
penguin <- penguins %>% 
  mutate(across(c(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g), as.numeric)) %>%
  filter(sex != "")

# 设置na.action避免模型拟合到不同数据集
options(na.action = "na.fail")

# 构建模型
model1 <- lm(bill_length_mm~bill_depth_mm+flipper_length_mm+body_mass_g, data=penguin)

# 初始化并行集群
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)

# 导出模型并加载包
clusterExport(cl, "model1")
clusterEvalQ(cl, library("MuMIn"))

# 运行并行dredge
combinations1 <- parLapply(cl, model1, MuMIn::dredge)

# 停止集群
stopCluster(cl)

运行后报错:

Error in checkForRemoteErrors(val) :
7 nodes produced errors; first error: no 'nobs' method is available


错误原因

  • parLapply使用逻辑错误:该函数会将第二个参数的每个元素单独传给第三个函数。直接传入model1(一个lm对象)时,它会被拆分成模型的各个组件(如系数、残差等),每个子进程拿到的不是完整模型,而是模型的某个部分,导致dredge无法识别对象类型,找不到nobs(观测数)方法。
  • 额外隐患:即使传递完整模型,子进程可能无法访问模型依赖的原始数据集(模型的环境绑定在主进程),也会导致拟合失败。

解决方法

方法1:使用MuMIn自带的并行支持(推荐)

MuMIn本身集成了并行功能,无需手动调用parLapply,只需设置mc.cores参数即可:

library(palmerpenguins)
library(MuMIn)
library(dplyr)

# 数据处理同前
penguin <- penguins %>% 
  mutate(across(c(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g), as.numeric)) %>%
  filter(sex != "")

options(na.action = "na.fail")
model1 <- lm(bill_length_mm~bill_depth_mm+flipper_length_mm+body_mass_g, data=penguin)

# 开启多核并行(设置为可用核心数-1)
options(mc.cores = detectCores() - 1)

# 直接运行dredge,自动并行
combinations1 <- dredge(model1)

# 关闭并行(可选)
options(mc.cores = 1)

注:Windows系统下mc.cores可能无法直接生效,此时需要先初始化集群并调用MuMIn的clusterSetup:

library(parallel)
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)
clusterEvalQ(cl, library(MuMIn))
clusterSetup(cl)

combinations1 <- dredge(model1)

stopCluster(cl)

方法2:修正parLapply的用法

如果一定要手动用parLapply,需要将模型放在一个列表中,确保每个子进程拿到完整的模型对象,同时导出模型依赖的数据集:

library(palmerpenguins)
library(MuMIn)
library(dplyr)
library(parallel)

# 数据处理同前
penguin <- penguins %>% 
  mutate(across(c(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g), as.numeric)) %>%
  filter(sex != "")

options(na.action = "na.fail")
model1 <- lm(bill_length_mm~bill_depth_mm+flipper_length_mm+body_mass_g, data=penguin)

# 初始化集群
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores)

# 导出模型和数据集,加载必要包
clusterExport(cl, c("model1", "penguin"))
clusterEvalQ(cl, library(MuMIn))

# 将模型放入列表,确保parLapply传递完整对象
combinations1 <- parLapply(cl, list(model1), MuMIn::dredge)

# 停止集群
stopCluster(cl)

# 提取结果(因为返回的是列表,取第一个元素)
combinations1 <- combinations1[[1]]

内容的提问来源于stack exchange,提问作者Jason Edelkind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:03:21