将系数变量名从glmnet提取到data.frame中

时间:2015-01-06 14:29:42

标签: r glmnet

我想提取glmnet生成的模型系数并从中创建SQL查询。函数coef(cv.glmnet.fit)生成一个“dgCMatrix”对象。当我使用as.matrix将其转换为矩阵时,变量名称将丢失,只留下系数值。

我知道可以在屏幕上打印系数,但是可以将名称写入数据框吗?

有人可以协助提取这些名字吗?

8 个答案:

答案 0 :(得分:22)

<强>更新 我的回答的前两个评论都是正确的。我只是为后人保留了答案。

以下答案很简短,有效,不需要任何其他套餐:

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开始。


OLD ANSWER :(仅为子孙后代保留) 尝试以下几行:

非零系数:

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)]

然后将它们作为数据框放在一起是明确的,但是如果你想要那部分代码,请告诉我。


答案 1 :(得分:6)

名称应该可以dimnames(coef(cv.glmnet.fit))[[1]]访问,因此以下内容应将系数名称和值都放入data.frame: data.frame(coef.name = dimnames(coef(GLMNET))[[1]], coef.value = matrix(coef(GLMNET)))

答案 2 :(得分:4)

检查broom包裹。它具有tidy函数,可将不同R对象(包括glmnet)的输出转换为data.frames。

答案 3 :(得分:4)

在上面的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就绪表。

答案 4 :(得分:2)

使用 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开始。

答案 5 :(得分:2)

# 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"))
}

没有tibble:

tidy_coef2 <- function(x){
    x <- coef(x)
    data.frame(term=rownames(x),
               estimate=matrix(x)[,1],
               stringsAsFactors = FALSE)
}

答案 6 :(得分:2)

在这里,我编写了一个可重现的示例,并使用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

答案 7 :(得分:1)

假设您知道如何获得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

请注意,上面的示例意味着二项分布,但步骤可以应用于任何其他类型。

相关问题