首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:%*%需要数值/复矩阵/向量参数;交叉验证glmmTMB模型

错误:%*%需要数值/复矩阵/向量参数;交叉验证glmmTMB模型
EN

Stack Overflow用户
提问于 2022-01-19 21:11:06
回答 1查看 131关注 0票数 1

我正在将为glmer/merMod模型编写的一些k折叠交叉验证代码改编为glmmTMB模型框架。这一切似乎都很好,直到我尝试使用模型的输出与训练数据相匹配来预测和指数值到一个矩阵(然后分解成分位数/桶数来评估预测性能)。我可以让这一行使用glmer模型工作,但是当我使用glmmTMB运行相同的模型时,我得到了Error in model.matrix: requires numeric/complex matrix/vector arguments,还有很多其他文章讨论了这个错误代码,我尝试将数据框架转换成矩阵形式,并没有运气地改变协变量的类。分别在%*%之前和之后运行这些部件,但是合并后我会得到错误。对于上下文,这段代码将使用use/availability数据运行,因此示例变量可能没有意义,但问题得到了充分的显示。对于发生了什么,有什么建议吗?

代码语言:javascript
复制
library(lme4)
library(glmmTMB)

# Example with mtcars dataset
data(mtcars)

# Model both with glmmTMB and lme4
m1 <- glmmTMB(am ~ mpg + wt + (1|carb), family = poisson, data=mtcars)
m2 <- glmer(am ~ mpg + wt + (1|carb), family = poisson, data=mtcars)

#--- K-fold code (hashed out sections are original glmer version of code where different)---

# define variables
k <- 5
mod <- m1 #m2
dt <- model.frame(mod) #data used

reg.list <- list() # initialize object to store all models used for cross validation
  
# finds the name of the response variable in the model dataframe
  resp <- as.character(attr(terms(mod), "variables"))[attr(terms(mod), "response") + 1]
    
# define column called sets and populates it with character "train"
  dt$sets <- "train"
    
# randomly selects a proportion of the "used"/am records (i.e. am = 1) for testing data 
    dt$sets[sample(which(dt[, resp] == 1), sum(dt[, resp] == 1)/k)] <- "test"
    
# updates the original model using only the subset of "trained" data
    reg <- glmmTMB(formula(mod), data = subset(dt, sets == "train"), family=poisson,
                   control = glmmTMBControl(optimizer = optim, optArgs=list(method="BFGS")))

    #reg <- glmer(formula(mod), data = subset(dt, sets == "train"), family=poisson,
    #            control = glmerControl(optimizer = "bobyqa", optCtrl=list(maxfun=2e5)))
    
 reg.list[[i]] <- reg # store models
    
# uses new model created with training data (i.e. reg) to predict and exponentiate values 
      predall <- exp(as.numeric(model.matrix(terms(reg), dt) %*% glmmTMB::fixef(reg)))
     #predall <- exp(as.numeric(model.matrix(terms(reg), dt) %*% lme4::fixef(reg)))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-20 01:21:07

没有仔细研究代码:glmmTMB::fixef(reg)返回一个列表(包含元素cond (条件模型参数)、zi (零通胀参数)、disp (色散参数)而不是向量。

如果您用glmmTMB::fixef(reg)[["cond"]]替换此位,它可能会起作用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70777801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档