gpt4 book ai didi

r - R 中对一组不同解释变量的并行面板 logit 计算

转载 作者:行者123 更新时间:2023-12-02 07:40:10 26 4
gpt4 key购买 nike

我是 R 并行计算的初学者。我遇到了 doParallel 包,我认为它对我的情况可能有用。

以下代码旨在并行评估多个 pglm 回归:

require("foreach")
require("doParallel")

resVar <- sample(1:6,100,TRUE)
x1 <- 1:100
x2 <- rnorm(100)
x3 <- rchisq(100, 2, ncp = 0)
x4 <- rweibull(100, 1, scale = 1)
Year <- sample(2011:2014,100,replace=TRUE)
X <- data.frame(resVar,x1,x2,x3,x4,Year)

facInt = 1:4 # no factors
#find all possible combinations
cmbList <- lapply(2, function(nbFact) {
allCmbs <- t(combn(facInt, nbFact))
dupCmbs <- combn(1:4, nbFact, function(x) any(duplicated(x)))
allCmbs[!dupCmbs, , drop = FALSE] })

noSubModel <- c(0, sapply(cmbList, nrow))
noModel <- sum(noSubModel)
combinations <- cmbList[[1]]
factors <- X[,c("x1","x2","x3","x4")]
coeff_vars <- matrix(colnames(factors)[combinations[1:length(combinations[,1]),]],ncol = length(combinations[1,]))

yName <- 'resVar'
cl <- makeCluster(4)
registerDoParallel(cl)
r <- foreach(subModelInd=1:noSubModel[2], .combine=cbind) %dopar% {
require("pglm")
vars <- coeff_vars[subModelInd,]
formula <- as.formula(paste('as.numeric(', yName, ')',' ~ ', paste(vars,collapse=' + ')))
XX<-X[,c("resVar",vars,"Year")]
ans <- pglm(formula, data = XX, family = ordinal('logit'), model = "random", method = "bfgs", print.level = 3, R = 5, index = 'Year')

coefficients(ans)

}
stopCluster(cl)
cl <- c()

当我尝试通过以下方式并行化它时,它不起作用。我收到以下错误:

Error in { : task 1 failed - "object 'XX' not found"

一组按顺序评估的多个 pglm 回归有效:

require("pglm")
r <- foreach(icount(subModelInd), .combine=cbind) %do% {
vars <- coeff_vars[subModelInd,]
formula <- as.formula(paste('as.numeric(', yName, ')',' ~ ', paste(vars,collapse=' + ')))
XX<-X[,c("resVar",vars,"Year")]
ans <- pglm(formula, data = XX, family = ordinal('logit'), model = "random", method = "bfgs", print.level = 3, R = 5, index = 'Year')

coefficients(ans)

}

有人可以建议如何正确并行化此任务吗?

谢谢!

最佳答案

是的,pglm 看起来确实存在问题。以及它访问变量的方式。一个简单的修复方法是分配 XX到全局变量中,即更改

XX<-X[,c("resVar",vars,"Year")]

assign("XX", X[,c("resVar",vars,"Year")], pos = 1)

这应该可以解决问题,因为每个集群都作为单独的进程运行(据我所知,不是单独的线程),因此两个进程/线程尝试使用 XX 不会出现问题。变量。

我添加了两行 - a set.seed(131) coefficients(ans) 之后还有另一行,即

set.seed(131)

... rest of your code ....
coefficients(ans)

write(paste0(coefficients(ans)[1],"\n"),file="c:\\temp\\r\\out.txt",append=TRUE)

并且在文件中得到一致的 6 行(相同的数字,但显然顺序不同):

0.703727602527463
1.03799340156792
1.15220874833614
1.30381769320552
1.42656613017171
1.77287504108163

这也应该适合你。

关于r - R 中对一组不同解释变量的并行面板 logit 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com