Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathClassify and Evaluate: Logistic Regression to Cross-Validation
  1. 1
    Logistic Regression and the Sigmoid: Score, Squash, Decide
  2. 2
    Logistic Regression in scikit-learn: predict, predict_proba and Softmax
  3. 3
    Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
  4. 4
    Precision, Recall and F1 Score: Two Questions and One Balance
  5. 5
    ROC Curve, AUC and Choosing a Classification Threshold
  6. 6
    Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
  7. 7
    Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 3 of 7

Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors

On 20,000 card payments with 1% fraud, a model that never looks scores 99% accuracy and catches nothing. The confusion matrix shows what accuracy hides: 21 frauds caught, 29 missed.

Chaand Sheikh

·27 November 2026Classification and Evaluation

What you will learn

  • Explain the accuracy paradox on imbalanced data
  • Set a baseline with DummyClassifier
  • Read TN, FP, FN and TP from confusion_matrix
  • Tell a Type I error from a Type II error

Before you start

  • Logistic Regression in scikit-learn
  • Train-Test Split and Data Leakage

A smoke alarm can make two mistakes. It can beep at burnt toast: a false alarm, annoying but nobody gets hurt. Or it can stay silent in a real fire: a disaster.

Accuracy counts both mistakes the same, and they're not the same at all. In this article a model is 99.4% accurate and still misses most of the fraud. The confusion matrix is how you see it.

The data: 20,000 payments, 1% fraud

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

df = pd.read_csv("payments.csv")
X = df.drop(columns="fraud")
y = df["fraud"]
print(df.shape, y.value_counts().to_dict())
(20000, 7) {0: 19800, 1: 200}

Six input columns and a fraud label: 1 for fraud, 0 for a normal payment. 19,800 normal, 200 fraud. That's 1%.

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42)
print(y_test.value_counts().to_dict())
{0: 4950, 1: 50}

stratify=y keeps the 1% in the test part: 4,950 normal payments and 50 frauds.

A model that never looks

Before any real model, build a lazy one. DummyClassifier(strategy="most_frequent") ignores every column and always answers the most common label: normal.

lazy = DummyClassifier(strategy="most_frequent")
lazy.fit(X_train, y_train)
pred = lazy.predict(X_test)
caught = pred[y_test == 1].sum()
print("accuracy:", lazy.score(X_test, y_test))
print("frauds caught:", caught, "of", y_test.sum())
accuracy: 0.99
frauds caught: 0 of 50

99% accuracy, zero frauds caught. A smoke alarm with the battery taken out.

When one class is rare, the lazy answer is right almost every time, so accuracy looks great. This is the accuracy paradox. The lazy model is your baseline: the score any real model has to beat.

A real model

model = LogisticRegression()
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
print("accuracy:", round(acc, 3))
accuracy: 0.994

0.994, only a little above the lazy 0.99. Is it good? Accuracy alone can't say.

The confusion matrix: four boxes

Every prediction lands in one of four boxes. In scikit-learn, rows are the actual label and columns are the predicted label.

The four boxes of the fraud model predicted normal fraud actual normal fraud True negative (TN) 4,949 normal, left alone False positive (FP) 1 false alarm, Type I False negative (FN) 29 missed fire, Type II True positive (TP) 21 fraud, caught
The diagonal (green) is right. The other two boxes are the two kinds of mistake. For this fraud model, 29 of the 50 frauds land in the false-negative box.
cm = confusion_matrix(y_test, model.predict(X_test))
print(cm)
[[4949    1]
 [  29   21]]

For two classes, ravel() unpacks the four numbers in a fixed order: TN, FP, FN, TP.

tn, fp, fn, tp = cm.ravel()
print("TN", tn, "FP", fp, "FN", fn, "TP", tp)
TN 4949 FP 1 FN 29 TP 21

4,949 normal payments correctly left alone. One false alarm. 29 frauds missed. 21 caught. And 29 + 21 is the 50 frauds in the test part.

So the model is 99.4% accurate, and still 29 of the 50 frauds slip through. Accuracy never told us that.

The same boxes, drawn

ConfusionMatrixDisplay.from_estimator(
    model, X_test, y_test,
    display_labels=["normal", "fraud"], cmap="Blues");
scikit-learn confusion matrix plot with True label on the left (normal, fraud) and Predicted label along the bottom (normal, fraud). Cells: normal-normal 4949 in dark blue, normal-fraud 1, fraud-normal 29, fraud-fraud 21.
ConfusionMatrixDisplay predicts and draws in one call. True label on the left, predicted label along the bottom; each row adds up to its real count.

Type I and Type II errors

The two mistakes have formal names. Think of a medical test:

  • Type I error = false positive. A healthy person is told "you're sick". Extra tests, some worry, then it's cleared.
  • Type II error = false negative. A sick person is told "you're healthy" and goes home untreated. Much worse.

Which one hurts more depends on the problem. For illness and fraud, a Type II miss hurts more. For a spam filter, a Type I error (good mail sent to spam) hurts more.

Common mistakes

  • Reporting accuracy on imbalanced data without a baseline. 0.994 sounds great until you see the lazy model scores 0.99.
  • Mixing up rows and columns. In scikit-learn, rows are the truth. Other tools may flip it, so check the labels.
  • Forgetting stratify=y. With only 200 frauds, a plain split can put noticeably more or fewer in the test part.

Quick recap

IdeaFraud model
Lazy baseline (DummyClassifier)accuracy 0.99, 0 of 50 caught
Logistic regression accuracy0.994
TN / FP / FN / TP4,949 / 1 / 29 / 21
Type I error (false alarm)FP = 1
Type II error (missed fire)FN = 29

Try it yourself

Use DummyClassifier(strategy="stratified", random_state=42) as the baseline and print its confusion matrix. How many frauds does it catch? Then turn the four boxes into scores in Precision, Recall and F1.

The notebook and payments.csv are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Logistic Regression in scikit-learn: predict, predict_proba and Softmax
Next →
Precision, Recall and F1 Score: Two Questions and One Balance
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • The data: 20,000 payments, 1% fraud
  • A model that never looks
  • A real model
  • The confusion matrix: four boxes
  • The same boxes, drawn
  • Type I and Type II errors
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.