Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Machine Learning
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. MLOps and Production ML

      The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold

      Beat the dumbest guess first, then put a price on every mistake. On synthetic payments, a $200 miss and a $10 false alarm move the cheapest cut from 0.5 to 0.07, which costs $3,400 on the test set against $5,810 at the default.

      Chaand Sheikh

      ·27 November 2026Experiments and Model Quality

      What you will learn

      • Build a baseline ladder: never flag, one simple rule, then the model
      • Turn false negatives and false positives into a cost in dollars
      • Sweep every threshold and pick the cheapest one on validation
      • Check the chosen cut once on the test set and on 20 other splits

      Before you start

      • Why Accuracy Lies: The Confusion Matrix
      • ROC Curve, AUC and Choosing a Classification Threshold

      Accuracy and F1 tell you how often a model is wrong. They don't tell you what being wrong costs. In this article we do two things: beat the dumbest guess first, and then put a price on every mistake and find the cheapest cut.

      The data is the payments file from Why Accuracy Lies and ROC, AUC and Choosing a Threshold: 20,000 rows, 1% fraud, made with make_classification, so it's synthetic. Same split too: 11,250 rows to fit, 3,750 for validation (37 frauds) and 5,000 for test (50 frauds).

      A smoke alarm and two kinds of wrong

      You burn some toast and the smoke alarm beeps. That's a false alarm, and it costs you a sigh. Now a real fire, and the alarm stays quiet. That's a missed fire, and it costs you the house.

      In payments, a good payment that gets held back is the false alarm (a false positive). A fraud that goes through is the missed fire (a false negative). Two mistakes, two very different prices. The question is, how different?

      The baseline ladder

      A number means nothing until you have something to compare it with. So we build three rungs:

      from sklearn.dummy import DummyClassifier
      from sklearn.linear_model import LogisticRegression
      from sklearn.tree import DecisionTreeClassifier
      
      from common import split
      
      X_fit, X_val, X_test, y_fit, y_val, y_test = split()
      
      never = DummyClassifier().fit(X_fit, y_fit)
      rule = DecisionTreeClassifier(max_depth=1, random_state=42)
      rule.fit(X_fit, y_fit)
      model = LogisticRegression().fit(X_fit, y_fit)
      
      for name, m in [("never flag", never), ("one rule", rule),
                      ("model", model)]:
          caught = m.predict(X_val)[y_val == 1].sum()
          print(f"{name:<11}accuracy {m.score(X_val, y_val):.3f}"
                f"  caught {caught} of {y_val.sum()}")
      never flag accuracy 0.990  caught 0 of 37
      one rule   accuracy 0.992  caught 8 of 37
      model      accuracy 0.993  caught 11 of 37
      • Never flag: a DummyClassifier that always says normal. The dumbest baseline.
      • One rule: a decision tree with max_depth=1 is a single question. Here it asks: is v6 at most 1.79?
      • The model: logistic regression.

      Accuracy is 0.990, 0.992 and 0.993. They almost look the same. But frauds caught go 0, 8, 11. One number hides the story. The model has to beat the dumb guess, then the simple rule.

      A price on every mistake

      At the top of common.py we set two numbers. These are example costs I've assumed; they're not real, so use your own.

      import numpy as np
      import pandas as pd
      from sklearn.linear_model import LogisticRegression
      from sklearn.metrics import confusion_matrix
      from sklearn.model_selection import train_test_split
      
      MISS = 200    # example cost of one missed fraud
      ALARM = 10    # example cost of one false alarm
      
      
      def cost(y, flag, miss=MISS, alarm=ALARM):
          tn, fp, fn, tp = confusion_matrix(y, flag).ravel()
          return fn * miss + fp * alarm
      
      
      def cost_curve(p, y, miss=MISS, alarm=ALARM):
          cuts = np.round(np.arange(0.01, 1.0, 0.01), 2)
          costs = [cost(y, p >= t, miss, alarm) for t in cuts]
          return cuts, costs
      
      
      def split(seed=42):
          df = pd.read_csv("payments.csv")
          X, y = df.drop(columns="fraud"), df["fraud"]
          X_tr, X_test, y_tr, y_test = train_test_split(
              X, y, test_size=0.25, stratify=y, random_state=seed)
          X_fit, X_val, y_fit, y_val = train_test_split(
              X_tr, y_tr, test_size=0.25, stratify=y_tr, random_state=seed)
          return X_fit, X_val, X_test, y_fit, y_val, y_test
      
      
      def scores(seed=42):
          X_fit, X_val, X_test, y_fit, y_val, y_test = split(seed)
          model = LogisticRegression().fit(X_fit, y_fit)
          return (model.predict_proba(X_val)[:, 1], y_val,
                  model.predict_proba(X_test)[:, 1], y_test)

      cost reads the four boxes of the confusion matrix and multiplies only the two mistakes by their prices. For the model at the default cut of 0.5 on validation, the boxes are 3,713 true negatives, 0 false alarms, 26 missed frauds and 11 caught:

      26 misses x $200 = $5,200
       0 alarms x  $10 =     $0
      total            = $5,200

      A correct answer costs nothing here. Only the two mistakes have a price.

      The same ladder, in money

      price_tag.py builds the same three rungs as above, then prices each one with cost:

      for name, m in [("never flag", never), ("one rule", rule),
                      ("model at 0.5", model)]:
          print(f"{name:<13}costs {cost(y_val, m.predict(X_val)):>6,}")
      never flag   costs  7,400
      one rule     costs  5,800
      model at 0.5 costs  5,200

      Never flag misses all 37 frauds. The rule misses 29. The model saves $600 over the rule and $2,200 over never flagging. The rule is the fair opponent: beat the dumb guess, then beat the simple rule.

      Try every cut, keep the cheapest

      Now we have a price, so which cut is cheapest? cost_curve tries every cut from 0.01 to 0.99:

      from common import scores, cost_curve
      
      p_val, y_val, p_test, y_test = scores()
      cuts, costs = cost_curve(p_val, y_val)
      best = cuts[costs.index(min(costs))]
      print("cost at 0.50:", costs[49])
      print("cheapest cut:", best, "costs", min(costs))
      cost at 0.50: 5200
      cheapest cut: 0.07 costs 3900
      Cost of every cut on the validation set $3,000 $4,000 $5,000 $6,000 $7,000 0 0.25 0.5 0.75 1.0 cut (flag a payment when its score is at least this) cheapest: 0.07, $3,900 default 0.5: $5,200
      Validation cost at every cut, drawn from the project's own run. The cheapest cut is 0.07 at $3,900; the default 0.5 costs $5,200.

      Moving the cut from 0.5 to 0.07 saves $1,300 on validation. For these costs, the default cut isn't the cheapest one. (Too low is expensive too: at 0.01 the false alarms pile up and the cost climbs to $6,580.)

      Change the price and the cut moves

      Who decided a miss costs $200? I did, as an example. In real life, the business decides. So let's try three prices for a missed fraud:

      for miss in (50, 200, 500):
          cuts, costs = cost_curve(p_val, y_val, miss=miss)
          best = cuts[costs.index(min(costs))]
          print(f"missed fraud ${miss}: cheapest cut {best}")
      missed fraud $50: cheapest cut 0.25
      missed fraud $200: cheapest cut 0.07
      missed fraud $500: cheapest cut 0.03

      The dearer the miss, the lower the cut. That's why the threshold is a business decision: because the price is.

      The test set, once

      Three cuts, all chosen on validation: the default 0.5, the best-F1 cut from the ROC article (0.258), and our cost cut (0.07). Now we touch the test set, once.

      from sklearn.metrics import precision_recall_curve
      
      from common import scores, cost, cost_curve
      
      p_val, y_val, p_test, y_test = scores()
      cuts, costs = cost_curve(p_val, y_val)
      prec, rec, thr = precision_recall_curve(y_val, p_val)
      f1 = 2 * prec * rec / (prec + rec + 1e-12)
      
      picks = {"0.50": 0.5, "F1 cut": thr[f1[:-1].argmax()],
               "cost cut": cuts[costs.index(min(costs))]}
      for name, t in picks.items():
          print(f"{name:<9}t={t:.3f}  test cost {cost(y_test, p_test >= t):>6,}")
      never = cost(y_test, [0] * len(y_test))
      print("never flag test cost", f"{never:,}")
      0.50     t=0.500  test cost  5,810
      F1 cut   t=0.258  test cost  5,020
      cost cut t=0.070  test cost  3,400
      never flag test cost 10,000
      Cut on testFrauds caught (of 50)False alarmsCost
      0.5 (default)211$5,810
      0.07 (cost cut)3540$3,400
      never flag00$10,000

      The cost cut accepts 40 false alarms to catch 14 more frauds, because false alarms are cheap. The cut chosen on validation also won on the test set.

      Is the cut luck? Try 20 splits

      Validation has only 37 frauds, so is 0.07 just luck? For each of 20 seeds, we make a new split, find the cheapest cut on validation and compare it with 0.5 on test:

      from common import scores, cost, cost_curve
      
      wins, used = 0, []
      for seed in range(20):
          p_val, y_val, p_test, y_test = scores(seed)
          cuts, costs = cost_curve(p_val, y_val)
          best = cuts[costs.index(min(costs))]
          used.append(best)
          wins += cost(y_test, p_test >= best) < cost(y_test, p_test >= 0.5)
      print(f"cost cut beat 0.50 on test in {wins} of 20 splits")
      print("cheapest cut ranged", min(used), "to", max(used))
      cost cut beat 0.50 on test in 20 of 20 splits
      cheapest cut ranged 0.03 to 0.16

      The cost cut won every time, but the cheapest cut itself moved between 0.03 and 0.16. Our 0.07 sits inside that range. The cut moves with the split, so treat it as a range, not a magic number.

      One more thing: these scores come from an uncalibrated model, so "0.07" is a position on the model's scale, not a 7% chance. Whether you can read the score as a probability is the topic of Calibration.

      Common mistakes

      • Comparing only to zero. Always run the dumb guess and a one-rule baseline. Accuracy 0.990 vs 0.993 hid 0 vs 11 frauds caught.
      • Keeping 0.5 because it's the default. With a $200 miss and a $10 alarm, 0.5 cost $1,300 more on validation.
      • Inventing the prices yourself. The costs here are examples. The real ones come from the business.
      • Choosing the cut on the test set. Pick it on validation, then look at test once.
      • Trusting one split. Re-split and report a range for the cut.

      Recap

      StepResult on this data
      Baseline ladder (validation)caught 0 / 8 / 11 of 37
      Price each mistakemiss $200, alarm $10 (assumed)
      Sweep the cut0.07 costs $3,900 vs $5,200 at 0.5
      Change the price$50 gives 0.25, $500 gives 0.03
      Test once$3,400 vs $5,810 at 0.5
      20 splitswon 20 of 20, cut ranged 0.03 to 0.16

      Try it yourself

      Set MISS = 1000 in common.py and run sweep.py again. Does the cheapest cut move up or down? Predict the answer before you run it.

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

      Join free on Skool →
      ← Previous
      MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      Next →
      Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      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
      Python Virtual Environments: One Project, One Toolbox

      Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.

      Git and GitHub Fundamentals: Commits, Branches, Push and Pull

      The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.

      Testing a FastAPI App with pytest: Three Small Tests

      A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.

      Config and Logging Instead of Hard-Coded Values in ML Training

      Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.

      On this page
      • A smoke alarm and two kinds of wrong
      • The baseline ladder
      • A price on every mistake
      • The same ladder, in money
      • Try every cut, keep the cheapest
      • Change the price and the cut moves
      • The test set, once
      • Is the cut luck? Try 20 splits
      • Common mistakes
      • 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.