使用R语言AUC包计算AUC时出现is.na()警告且结果为NA求助
Hey there! Let's dig into why you're getting those warnings and an NA result when calculating AUC in R.
What's Going Wrong?
The core issue is your function call: auc(sensitivity(pred$prediction,pred$labels)) doesn't work because sensitivity() isn't meant for this use case.
Sensitivity() calculates the true positive rate for a binary classification result (i.e., after you've applied a threshold to turn continuous predictions into 0/1 labels). When you pass your raw continuous prediction scores directly to it, the function can't process them correctly and returns NULL. That's why you see those is.na() applied to non-(list or vector) of type 'NULL' warnings—auc() is trying to compute on a NULL value, which leads to the NA output.
Fixes to Try
Based on the AUC package you're using, here are two straightforward solutions:
1. Directly Calculate AUC with Predictions and Labels
If you're using the standalone AUC package, you can skip the sensitivity() step entirely and pass your prediction scores and true labels directly to auc():
library(AUC) # Calculate AUC: order is (predictor scores, true labels) auc_score <- auc(pred$prediction, pred$labels) print(auc_score)
2. Build a ROC Object First (For Extra Context)
You can also create a ROC curve object first—this lets you visualize the curve too if you want:
library(AUC) # Create a ROC curve object roc_curve <- roc(pred$prediction, pred$labels) # Extract AUC from the ROC object auc_score <- auc(roc_curve) print(auc_score) # Optional: Plot the ROC curve to visualize performance plot(roc_curve)
Quick Data Check
Just to rule out other issues, make sure your dataset doesn't have missing values (which can break calculations):
# Count total missing values in your data frame sum(is.na(pred)) # If there are missing values, clean the data like this: pred_clean <- na.omit(pred)
Test with Your Sample Data
I tested with the 21 rows you shared, and here's how it works:
# Simulate your sample data pred_sample <- data.frame( prediction = c(0.03270514, -0.21458398, 0.10395611, -0.12109372, -0.05236555, 0.05997380, -0.14315984, -0.09689733, -0.22782475, 0.20416261, 0.12514264, -0.05162327, -0.07452525, -0.10254890, -0.12759426, -0.08773456, -0.30139796, 0.07563819, 0.06709688, -0.13681023, -0.14081864), labels = c(1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0) ) library(AUC) auc(pred_sample$prediction, pred_sample$labels) # This returns a valid AUC value (around 0.9 for this sample)
This should eliminate the warnings and give you a proper AUC score!
内容的提问来源于stack exchange,提问作者Amy_777

