簡體   English   中英

如何使用插入符包 train() 和 varImp() 在 R 中顯示邏輯回歸的系數值和變量重要性

[英]How to show the coefficient values and variable importance for logistic regression in R using caret package train() and varImp()

我們正在進行探索性邏輯回歸,並試圖確定變量在預測結果中的重要性。 我們正在使用 caret 包中的 train() 和 varImp() 函數。 最終,我們想創建一個包含 3 列的表/數據框輸出:變量名稱、重要性和系數。 像這樣的輸出:

所需的輸出格式。

1個

下面是一些示例代碼來說明:

library(caret)

# Create a sample dataframe

my_DV <- c(0, 1, 0, 1, 1)
IV1 <- c(10, 40, 15, 35, 38)
IV2 <- c(1, 0, 1, 0, 1)
IV3 <- c(5, 4, 3, 2, 1)
IV4 <- c(5, 7, 3, 8, 9)
IV5 <- c(1, 2, 1, 2, 1)

df <- data.frame(my_DV, IV1, IV2, IV3, IV4, IV5)
df$my_DV <- as.factor(df$my_DV)
df$IV1 <- as.numeric(df$IV1)
df$IV2 <- as.factor(df$IV2)
df$IV3 <- as.numeric(df$IV3)
df$IV4 <- as.numeric(df$IV4)
df$IV5 <- as.factor(df$IV5)

# train model/perform logistic regression
model_one <- train(form = my_DV ~ ., data = df, trControl = trainControl(method = "cv", number = 5), 
    method = "glm", family = "binomial", na.action=na.omit)
summary(model_one)

# get the variable importance
imp <- varImp(model_one)
imp

我想獲取imp中的重要性值並將它們與model_one中的系數合並,但我對 R 還很陌生,我不知道該怎么做。

非常感謝任何建議!

這是獲得所需輸出的多種方法之一:

您將模型的摘要分配給一個對象,然后使用coef()函數提取系數,然后將其與變量名稱和相應的重要性綁定到一個數據框中。 然后,您可以使用order()根據重要性值對行進行排序。

sum_mod <- summary(model_one)
dat <- data.frame(VariableName = rownames(imp$importance), 
    Importance = imp$importance, 
    Coefficient = coef(sum_mod)[rownames(imp$importance),][,1], 
    row.names = NULL) 
dat <- dat[order(dat$Overall, decreasing = TRUE),]

結果:

  VariableName   Overall Coefficient
1          IV1 100.00000   1.0999732
4          IV4  74.48458   3.6665775
2         IV21  34.43803  -7.8831404
3          IV3   0.00000  -0.9166444

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM