⚡0 XP🔥0

Logistic Regression and Classification Metrics

Lesson 4 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Python

Classify with logistic regression and the sigmoid function, predict probabilities, choose thresholds, and evaluate with the confusion matrix, accuracy, precision, recall, F1-score and ROC-AUC.

Classification predicts a category: spam or not, pass or fail, fraud or genuine, which digit is in an image. Despite its name, logistic regression is a classification algorithm - and one of the most used models in industry because it is fast, simple and easy to explain.

From a line to a probability: the sigmoid#

Logistic regression computes a linear score z = w·x + b, then squashes it into a probability between 0 and 1 with the sigmoid function:

σ(z) = 1 / (1 + e^(-z))
▶ Try it YourselfPython
Ctrl + Enter to run
Output
z =  -6.0  ->  probability 0.002
z =  -2.0  ->  probability 0.119
z =  -0.5  ->  probability 0.378
z =   0.0  ->  probability 0.500
z =   0.5  ->  probability 0.622
z =   2.0  ->  probability 0.881
z =   6.0  ->  probability 0.998

If the probability is ≥ 0.5 (the default threshold), the model predicts class 1, otherwise class 0.

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

Logistic regression पहले एक score निकालता है (जैसे linear regression), फिर sigmoid उस score को 0 से 1 के बीच की probability में बदल देता है। Probability 0.5 या ज़्यादा हो तो model "हाँ" (class 1) कहता है, वरना "नहीं"। इस 0.5 को threshold कहते हैं और ज़रूरत के हिसाब से बदल सकते हैं।

A first classifier: pass or fail#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
1 hours: P(pass) = 0.09 -> predict fail
3 hours: P(pass) = 0.44 -> predict fail
4 hours: P(pass) = 0.68 -> predict pass
6 hours: P(pass) = 0.94 -> predict pass

predict_proba gives the probability of each class; predict applies the 0.5 threshold.

A real dataset: breast cancer diagnosis#

The breast cancer dataset has 569 tumours described by 30 measurements; the label is malignant (0) or benign (1).

▶ Try it YourselfPython
Ctrl + Enter to run
Output
Accuracy: 0.965
Confusion matrix (rows = actual, cols = predicted):
[[50  3]
 [ 2 88]]
              precision    recall  f1-score   support

   malignant      0.962     0.943     0.952        53
      benign      0.967     0.978     0.972        90

    accuracy                          0.965       143
   macro avg      0.964     0.961     0.962       143
weighted avg      0.965     0.965     0.965       143

The confusion matrix#

For a binary problem with "positive" = the class we care about:

Predicted positive Predicted negative
Actually positive True Positive (TP) False Negative (FN) - a miss
Actually negative False Positive (FP) - a false alarm True Negative (TN)

From it come the key metrics:

Metric Formula Question it answers
Accuracy (TP + TN) / all How often is the model right?
Precision TP / (TP + FP) When it says "positive", how often is it right?
Recall (sensitivity) TP / (TP + FN) Of all real positives, how many did it catch?
F1-score 2·P·R / (P + R) One number balancing precision and recall

Which matters depends on the cost of mistakes:

  • Cancer screening, fraud detection - missing a positive is dangerous → prioritise recall.
  • Spam filter - throwing away a real email is bad → prioritise precision.
  • Balanced classes, equal costs - accuracy or F1 is fine.
Common Mistake

On imbalanced data accuracy lies. If only 2 of 100 transactions are fraud, a model that always says "genuine" is 98% accurate and catches zero fraud. Look at precision, recall and the confusion matrix.

Changing the threshold#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
threshold 0.7: precision 1.000  recall 0.868
threshold 0.5: precision 0.980  recall 0.925
threshold 0.3: precision 0.962  recall 0.962
threshold 0.1: precision 0.895  recall 0.962
ROC-AUC: 0.9969

Lowering the threshold catches more malignant tumours (higher recall) at the cost of more false alarms (lower precision). ROC-AUC summarises performance over all thresholds: 1.0 is perfect, 0.5 is random guessing.

Tip

make_pipeline(StandardScaler(), LogisticRegression()) bundles scaling and the model, so the scaler is always fitted on training data only - even inside cross-validation.

Multi-class classification#

Logistic regression also handles more than two classes (it uses a "softmax" over classes):

▶ Try it YourselfPython
Ctrl + Enter to run
Output
accuracy: 0.933
[[15  0  0]
 [ 0 14  1]
 [ 0  2 13]]
probabilities of first test flower: [[0.289 0.71  0.001]]

Summary#

  • Logistic regression = linear score + sigmoid → probability; threshold 0.5 by default.
  • The confusion matrix counts TP, FP, FN, TN; precision, recall and F1 come from it.
  • Choose the metric by the cost of mistakes; accuracy misleads on imbalanced data.
  • Adjust the threshold to trade precision for recall; ROC-AUC measures ranking quality over all thresholds.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Compute metrics by hand

A spam filter's results on 100 emails: TP = 30, FP = 5, FN = 10, TN = 55. Compute accuracy, precision, recall and f1 (as floats) and print each rounded to 3 decimals.

2

Breast cancer classifier

Build a pipeline make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) on the breast cancer data (test_size=0.25, random_state=1, stratify=y). Store the test accuracy in acc and the recall for class 1 in rec and print both rounded to 3 decimals.

Quick Quiz

Q1.

The sigmoid function turns any number into...

Q2.

In disease screening, missing a sick patient is very costly. Which metric matters most?

Q3.

Why can accuracy be misleading?

Q4.

Precision answers...

Q5.

Lowering the decision threshold from 0.5 to 0.3 usually...