Statistical modeling with Python · Lesson 13 of 16

Evaluating logistic regression: ROC and AUC

How good is a logistic model? Confusion matrix, accuracy, precision and recall, ROC curve and AUC with sklearn.metrics, and how to choose a threshold.

About 17 minutes · code runs in your browser, nothing to install

A logistic model gives a probability for each row. To judge it you ask two questions: does it rank people well (are the ones who passed given higher probabilities?) and, once you turn probabilities into yes/no decisions, how many decisions are right? scikit-learn's sklearn.metrics has the tools; they work with any model's predictions, including statsmodels'.

From probabilities to decisions

Choose a threshold: predict "pass" when the probability is at least 0.5. Then count the four possible outcomes in a confusion matrix.

Pythoneditable
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

from sklearn.metrics import confusion_matrix

pred = (prob >= 0.5).astype("int64")
cm = confusion_matrix(df["passed"], pred)
print(pd.DataFrame(cm, index=["really failed", "really passed"],
                   columns=["predicted fail", "predicted pass"]))
Output
               predicted fail  predicted pass
really failed              30              13
really passed              12              45
  • True negatives (top left) and true positives (bottom right): right decisions.
  • False positives (top right): predicted pass, but failed.
  • False negatives (bottom left): predicted fail, but passed.

Accuracy, precision and recall

  • Accuracy: share of all decisions that are right. Misleading when one class is rare: if 95% pass, predicting "pass" for everyone gives 95% accuracy.
  • Precision: of those predicted to pass, the share who really passed. High precision = few false alarms.
  • Recall (sensitivity): of those who really passed, the share the model found. High recall = few missed cases.
  • F1: one number that balances precision and recall.
Pythoneditable
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

pred = (prob >= 0.5).astype("int64")
y = df["passed"]
print(f"accuracy:  {accuracy_score(y, pred):.3f}")
print(f"precision: {precision_score(y, pred):.3f}")
print(f"recall:    {recall_score(y, pred):.3f}")
print(f"F1:        {f1_score(y, pred):.3f}")
print(f"always guessing 'pass': {y.mean():.3f}")
Output
accuracy:  0.750
precision: 0.776
recall:    0.789
F1:        0.783
always guessing 'pass': 0.570

Always compare with the dumb baseline. Guessing "pass" for everyone is already right 57% of the time; the model reaches 75%, a real improvement. Precision and recall are both near 0.78: about one in five "pass" predictions is wrong, and about one in five students who passed is missed.

ROC curve and AUC: ranking quality

The threshold 0.5 is a choice. The ROC curve shows every threshold at once: the share of real passes found (recall, true positive rate) against the share of real fails wrongly flagged (false positive rate). The AUC (area under that curve) sums it up in one number: the chance that a random student who passed got a higher probability than a random student who failed. 0.5 = coin flip, 1.0 = perfect ranking.

Pythoneditable
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, roc_curve

auc = roc_auc_score(df["passed"], prob)
print(f"AUC: {auc:.3f}")
fpr, tpr, thresholds = roc_curve(df["passed"], prob)
plt.plot(fpr, tpr, color="crimson", label=f"model (AUC {auc:.2f})")
plt.plot([0, 1], [0, 1], color="grey", linestyle="--", label="coin flip")
plt.title("ROC curve")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate (recall)")
plt.legend()
plt.show()
Output
AUC: 0.857
Chart drawn by this code

Rough guide for AUC: 0.7 acceptable, 0.8 good, 0.9 excellent. These numbers were measured on the same students the model learned from, so they are a little optimistic; Comparing models: AIC and cross-validation measures them on new data.

Choosing a threshold

Lowering the threshold catches more of the real cases (higher recall) but raises more false alarms (lower precision). The right threshold depends on the costs. Here the positive class is "pass": a school that offers extra help to every student who might fail would rather flag too many students than miss one, so it would predict "pass" only when the model is quite sure, that is, use a higher threshold such as 0.7. Here, a threshold of 0.6 happens to give a slightly higher accuracy than 0.5 (see the exercise).

Pythoneditable
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

from sklearn.metrics import precision_score, recall_score

y = df["passed"]
for t in [0.3, 0.5, 0.7]:
    pred = (prob >= t).astype("int64")
    print(f"threshold {t}: predicted pass {int(pred.sum()):>2}, "
          f"precision {precision_score(y, pred):.2f}, recall {recall_score(y, pred):.2f}")
Output
threshold 0.3: predicted pass 73, precision 0.71, recall 0.91
threshold 0.5: predicted pass 58, precision 0.78, recall 0.79
threshold 0.7: predicted pass 47, precision 0.85, recall 0.70

✎ Exercise

Use the threshold 0.6 instead of 0.5. Print the confusion matrix (with confusion_matrix) and the accuracy with 3 decimals.

Hint: pred = (prob >= 0.6).astype("int64"), then confusion_matrix(df["passed"], pred).

Your codewrite your answer, then Run
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

from sklearn.metrics import confusion_matrix, accuracy_score

# your code here

Expected output:

[[35  8]
 [13 44]]
accuracy: 0.790
Show a solution
Solutioneditable
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
prob = model.predict(df)

from sklearn.metrics import confusion_matrix, accuracy_score

pred = (prob >= 0.6).astype("int64")
print(confusion_matrix(df["passed"], pred))
print(f"accuracy: {accuracy_score(df['passed'], pred):.3f}")
Output
[[35  8]
 [13 44]]
accuracy: 0.790

Check yourself

1. A model has AUC 0.85. What does it mean?

2. You lower the threshold from 0.5 to 0.3. What usually happens?

3. Only 3% of transactions are fraud. A model that never predicts fraud has accuracy…

Spotted a mistake on this page? Tell us