我想提取 glmnet 生成的模型系数并从中创建 SQL 查询。函数
coef(cv.glmnet.fit)
产生一个 'dgCMatrix
' 对象。当我使用 as.matrix
将其转换为矩阵时,变量名称会丢失,仅留下系数值。
我知道可以在屏幕上打印系数,但是可以将名称写入数据框吗?
有人可以帮忙提取这些名字吗?
更新: 我的答案的前两条评论都是正确的。我将答案保留在水平线以下,仅供后代参考。
以下答案很简短,它有效并且不需要任何其他包:
tmp_coeffs <- coef(cv.glmnet.fit, s = "lambda.min")
data.frame(name = tmp_coeffs@Dimnames[[1]][tmp_coeffs@i + 1], coefficient = tmp_coeffs@x)
+1 的原因是
@i
方法从 0 开始截距索引,但 @Dimnames[[1]]
从 1 开始。
旧答案:(仅供后代保留)尝试这些行:
非零系数:
coef(cv.glmnet.fit, s = "lambda.min")[which(coef(cv.glmnet.fit, s = "lambda.min") != 0)]
选择的功能:
colnames(regression_data)[which(coef(cv.glmnet.fit, s = "lambda.min") != 0)]
然后将它们放在一起作为数据框就可以了,但是如果您也想要这部分代码,请告诉我。
名称应可通过
dimnames(coef(cv.glmnet.fit))[[1]]
访问,因此以下应将系数名称和值放入 data.frame 中:
data.frame(coef.name = dimnames(coef(GLMNET))[[1]], coef.value = matrix(coef(GLMNET)))
基于上面 Mehrad 的解决方案,这里有一个简单的函数来打印仅包含非零系数的表格:
print_glmnet_coefs <- function(cvfit, s="lambda.min") {
ind <- which(coef(cvfit, s=s) != 0)
df <- data.frame(
feature=rownames(coef(cvfit, s=s))[ind],
coeficient=coef(cvfit, s=s)[ind]
)
kable(df)
}
上面的函数使用 knitr 中的
kable()
函数来生成 Markdown 就绪表。
有一种方法可以使用 coef() 到 glmnet() 对象(您的模型)。在索引 [[1]] 以下的情况下,指示多项逻辑回归中结果类的数量,也许对于其他模型,您应该删除它。
coef_names_GLMnet <- coef(GLMnet, s = 0)[[1]]
row.names(coef_names_GLMnet)[coef_names_GLMnet@i+1]
在这种情况下,row.names()索引需要递增(+1),因为coef()对象中的变量(数据特征)计数从0开始,但转换后字符向量计数从1开始。
在这里,我编写了一个可重现的示例,并使用
cv.glmnet
安装了一个二进制(逻辑)示例。 glmnet
模型拟合也可以。在这个示例的最后,我将非零系数和相关特征组装到一个名为 myResults
: 的 data.frame 中
library(glmnet)
X <- matrix(rnorm(100*10), 100, 10);
X[51:100, ] <- X[51:100, ] + 0.5; #artificially introduce difference in control cases
rownames(X) <- paste0("observation", 1:nrow(X));
colnames(X) <- paste0("feature", 1:ncol(X));
y <- factor( c(rep(1,50), rep(0,50)) ); #binary outcome class label
y
## [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [51] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## Levels: 0 1
## Perform logistic model fit:
fit1 <- cv.glmnet(X, y, family="binomial", nfolds=5, type.measure="auc"); #with K-fold cross validation
# fit1 <- glmnet(X, y, family="binomial") #without cross validation also works
## Adapted from @Mehrad Mahmoudian:
myCoefs <- coef(fit1, s="lambda.min");
myCoefs[which(myCoefs != 0 ) ] #coefficients: intercept included
## [1] 1.4945869 -0.6907010 -0.7578129 -1.1451275 -0.7494350 -0.3418030 -0.8012926 -0.6597648 -0.5555719
## [10] -1.1269725 -0.4375461
myCoefs@Dimnames[[1]][which(myCoefs != 0 ) ] #feature names: intercept included
## [1] "(Intercept)" "feature1" "feature2" "feature3" "feature4" "feature5" "feature6"
## [8] "feature7" "feature8" "feature9" "feature10"
## Asseble into a data.frame
myResults <- data.frame(
features = myCoefs@Dimnames[[1]][ which(myCoefs != 0 ) ], #intercept included
coefs = myCoefs [ which(myCoefs != 0 ) ] #intercept included
)
myResults
## features coefs
## 1 (Intercept) 1.4945869
## 2 feature1 -0.6907010
## 3 feature2 -0.7578129
## 4 feature3 -1.1451275
## 5 feature4 -0.7494350
## 6 feature5 -0.3418030
## 7 feature6 -0.8012926
## 8 feature7 -0.6597648
## 9 feature8 -0.5555719
## 10 feature9 -1.1269725
## 11 feature10 -0.4375461
# requires tibble.
tidy_coef <- function(x){
coef(x) %>%
matrix %>% # Coerce from sparse matrix to regular matrix.
data.frame %>% # Then dataframes.
rownames_to_column %>% # Add rownames as explicit variables.
setNames(c("term","estimate"))
}
没有小标题:
tidy_coef2 <- function(x){
x <- coef(x)
data.frame(term=rownames(x),
estimate=matrix(x)[,1],
stringsAsFactors = FALSE)
}
假设您知道如何获取 lambda,我发现了两种不同的方法来显示该特定 lambda 的所选模型中所需的预测变量。其中之一包括拦截。可以通过“glmnet”库中的cv.glmnet的方式使用交叉验证来获得 lambda。您可能只想查看每个方法的最后几行:
myFittedLasso = glmnet(x=myXmatrix, y=myYresponse, family="binomial")
myCrossValidated = cv.glmnet(x=myXmatrix, y=myYresponse, family="binomial")
myLambda = myCrossValidated$lambda.1se # can be simply lambda
# Method 1 without the intercept
myBetas = myFittedLasso$beta[, which(myFittedLasso$lambda == myLambda)]
myBetas[myBetas != 0]
## myPredictor1 myPredictor2 myPredictor3
## 0.24289802 0.07561533 0.18299284
# Method 2 with the intercept
myCoefficients = coef(myFittedLasso, s=myLambda)
dimnames(myCoefficients)[[1]][which(myCoefficients != 0)]
## [1] "(Intercept)" "myPredictor1" "M_myPredictor2" "myPredictor3"
myCoefficients[which(myCoefficients != 0)]
## [1] -4.07805560 0.24289802 0.07561533 0.18299284
请注意,上面的示例暗示二项式分布,但这些步骤可以应用于任何其他类型。
在使用
glmnet
框架中的 tidymodels
时,我遇到了类似的问题,其中模型是在工作流程中进行训练的,而 coef()
和上述解决方案都不起作用。
对我有用的是
glmnet:::coef.glmnet
代码的一部分:
# taken from glmnet:::coef.glmnet
coefs <- predict(x, "lambda.min", type = "coefficients", exact = FALSE)
dd <- cbind(
data.frame(var = rownames(coefs)),
as.data.table(as.matrix(coefs))
)