在glm()
中,可以使用以下语法通过逻辑回归对bernoulli [0,1]结果建模。
glm(bin ~ x, df, family = "binomial")
但是,您也可以执行二项式聚合回归,其中每个观察值代表一定数量的bernoulli试验产生的目标事件计数。例如,查看以下数据:
set.seed(1)
n <- 50
cov <- 10
x <- c(rep(0,n/2), rep(1, n/2))
p <- 0.4 + 0.2*x
y <- rbinom(n, cov, p)
使用这类数据,您在glm()
中使用略有不同的语法
mod <- glm(cbind(y, cov-y) ~ x, family="binomial")
mod
# output
# Call: glm(formula = cbind(y, cov - y) ~ x, family = "binomial")
#
# Coefficients:
# (Intercept) x
# -0.3064 0.6786
#
# Degrees of Freedom: 49 Total (i.e. Null); 48 Residual
# Null Deviance: 53.72
# Residual Deviance: 39.54 AIC: 178
我想知道是否可以在glmnet软件包中对这种类型的聚合二项式数据进行建模?如果是这样,语法是什么?
答案 0 :(得分:1)
是的,您可以按照以下步骤操作
set.seed(1)
n <- 50
cov <- 10
x <- c(rep(0,n/2), rep(1, n/2))
x = cbind(x, xx = c(rep(0.5,20), rep(0.7, 20), rep(1,10)))
p <- 0.4 + 0.2*x
y <- rbinom(n, cov, p)
我在此处添加了另一个协变量xx,因为glmnet接受至少两个协变量
在帖子中一目了然
mod <- glm(cbind(y, cov-y) ~ x, family="binomial")
mod
# output
# Call: glm(formula = cbind(y, cov - y) ~ x, family = "binomial")
# Coefficients:
# (Intercept) xx xxx
# 0.04366 0.86126 -0.64862
# Degrees of Freedom: 49 Total (i.e. Null); 47 Residual
# Null Deviance: 53.72
# Residual Deviance: 38.82 AIC: 179.3
在glmnet中,不进行正则化(lambda = 0)即可重现与glm类似的结果
library(glmnet)
fit = glmnet(x, cbind(cov-y,y), family="binomial", lambda=0)
coef(fit)
# output
# 3 x 1 sparse Matrix of class "dgCMatrix"
# s0
# (Intercept) 0.04352689
# x 0.86111234
# xx -0.64831806