[英]Get a confusion matrix , predicted probability plot, set a cutoff value using glmnet package in R
我試圖在 R 中使用 glmnet 包做邏輯套索。我找到了一種在互聯網上找到最佳 lambda 值的方法,但我不知道如何獲取混淆矩陣並繪制預測概率。 在這里,我制作了一個簡單的數據df
來演示我的嘗試。
df<-data.frame(date = c(20120324,20120329,20121216,20130216,20130725,20130729,20130930,20131015,20131124,20131225,
20140324,20140530,20140613,20140721,20140630,20150102,20150214,20150312,20150316,20150329),
temperature=c(35,36.5,34.3,37.8,39,40,34.5,35.9,35.8,36.1,37,35,36,36.3,37.8,38.1,39.2,34.5,34.9,35.2),
bmi=c(20,23,25,27,32,24,35,21,19,29,21,32,21,22,24,25,19,18,25,26),
asthma=c(1,1,0,1,0,0,1,1,0,0,1,1,1,0,1,0,0,1,1,0))
set.seed(101)
# Now Selecting 70% of data as sample from total 'n' rows of `df`
sample <- sample.int(n = nrow(df), size = floor(.7*nrow(df)), replace = F)
train <- df[sample, ]
test <- df[-sample, ]
x<-model.matrix(asthma ~ temperature+bmi,data=train)[,-1]
y<-as.matrix(train$asthma)
# Note alpha=1 for lasso only
library(glmnet)
glmmod <- glmnet(x, y, alpha=1, family="binomial")
# glmnet's approach: automated cross validation
cvfit = cv.glmnet(x, y)
# coeficients of the final model
coef_cv=coef(cvfit, s = "lambda.min")
在這里, asthma
是邏輯套索的二元響應變量。 temperature
和bmi
是因變量。 在我的代碼中,我可以獲得邏輯套索的最佳 lambda。 但是,在那之后,我不知道如何獲得混淆矩陣並繪制預測概率。 如果可能,我想更改最大化特異性和靈敏度的截止值,並從該截止值中獲取混淆矩陣。
我已經看到了一些代碼來做我提到的使用glm
的事情,但是我還沒有看到glmnet
的代碼。
我無法真正獲取您的示例數據來提供任何可用的預測,所以這里有一個glmnet
包附帶的示例:
library(glmnet)
data(BinomialExample)
x <- BinomialExample$x
y <- BinomialExample$y
# Fit a model using `cv.glmnet`
cfit <- cv.glmnet(x, y, family = "binomial")
# Use your model to make predictions
predicted_probabilities <- predict(cfit,newx=x,type="response")
# You can decide on an optimal threshold to turn your
# predicted probabilities into classifications e.g.
threshold <- 0.5
predicted_classes <- ifelse(predicted_probabilities > threshold,1,0)
# You can then make a confusion matrix like this:
table(predicted_classes,y)
# Or if you don't need to inspect the probabilities and pick a threshold
# you can produce one directly from your model object like this:
confusion.glmnet(cfit,newx=x,newy=y)
請注意,您可能希望使用與用於訓練模型的數據分開的測試數據生成混淆矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.