glmnet:我怎么知道我的响应的哪个因子水平在逻辑回归中被编码为 1

glmnet: How do I know which factor level of my response is coded as 1 in logistic regression

我有一个使用 glmnet 包制作的逻辑回归模型。我的响应变量被编码为一个因素,我将其水平称为 "a" 和 "b".

逻辑回归数学将两个 class 中的一个标记为“0”,另一个标记为“1”。逻辑回归模型的特征系数为正、负或零。如果特征 "f" 的系数为正,则增加测试观察 x 的 "f" 的值会增加模型 class 将 x 确定为 class 的概率"1".

我的问题是:给定一个 glmnet 模型,您如何知道 glmnet 如何将数据的因子标签 {"a", "b"} 映射到基础数学' 因子标签 {"0", "1"}?因为您需要知道这一点才能正确解释模型的系数。

您可以通过对 predict 函数应用于玩具观察时的输出进行试验来手动解决这个问题。但如果 glmnet 如何隐式处理该映射以加快解释过程,那就太好了。

谢谢!

看看 ?glmnethttps://cran.r-project.org/web/packages/glmnet/glmnet.pdf 的第 9 页):

y

response variable. ... For family="binomial" should be either a factor
with two levels, or a two-column matrix of counts or proportions (the 
second column is treated as the target class; for a factor, the last
level in alphabetical order is the target class) ...

现在还不清楚吗?如果您将 "a""b" 作为因子水平,则 "a" 编码为 0,而 "b" 编码为 1。

这样的待遇真的很标准。它与 R 代码如何自动生成因子或您自己如何对这些因子级别进行编码有关。看:

## automatic coding by R based on alphabetical order
set.seed(0); y1 <- factor(sample(letters[1:2], 10, replace = TRUE))
## manual coding
set.seed(0); y2 <- factor(sample(letters[1:2], 10, replace = TRUE),
                   levels = c("b", "a"))

# > y1
# [1] b a a b b a b b b b
# Levels: a b
# > y2
# [1] b a a b b a b b b b
# Levels: b a

# > levels(y1)
# [1] "a" "b"
# > levels(y2)
# [1] "b" "a"

无论您使用 glmnet() 还是简单地使用 glm(),都会发生同样的事情。