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

      Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs

      Make every training run leave a record: MLflow logs the settings, the scores and the whole pipeline for three values of C on a ticket-priority model, then the UI compares them, 20 re-splits test whether the 0.0108 gap is real, and the best run becomes version 1.

      Chaand Sheikh

      ·27 November 2026Experiments and Model Quality

      What you will learn

      • Point MLflow at a local SQLite file and an artifacts folder, with no server
      • Log params, metrics and a whole scikit-learn pipeline for every training run
      • Compare runs in the MLflow UI and judge whether a small gap is real
      • Register the best run and load it back by name and version

      Before you start

      • Pipelines and ColumnTransformer
      • MLOps in One Picture

      You try a few settings, look at a score, and an hour later you can't say which setting gave it. That's a very common problem. In this article our training code will leave a record behind: the settings, the scores and the model itself, for every run. The tool for the job is MLflow.

      The project is a ticket-priority model: it reads a support ticket and predicts whether its priority is high. The tickets are generated sample data (2,000 rows), so they're fine to play with.

      A lab notebook, not loose notes

      Imagine you try three settings for your model and write each on a sticky note: C = 0.1, C = 1 and C = 10. A week later someone asks which one was best. Nobody wrote it down, or the scores never made it onto the notes.

      Now picture a lab notebook. Every experiment gets its own line with the settings, the score and a tick that says the model is saved. The best one is right there, and you can repeat it. MLflow is that lab notebook, and the code writes each line, not you.

      tracking.py: where MLflow keeps everything

      One small helper says where things are kept. Every script calls it.

      """One place that says where MLflow keeps its data: inside this folder, offline."""
      import os
      from pathlib import Path
      
      import mlflow
      
      HERE = Path(__file__).parent
      # Docker sets MLFLOW_STORE_DIR to a shared volume
      STORE = Path(os.environ.get("MLFLOW_STORE_DIR", HERE))
      TRACKING_URI = f"sqlite:///{(STORE / 'mlflow.db').as_posix()}"
      ARTIFACTS = (STORE / "mlartifacts").as_uri()
      EXPERIMENT = "ticket-priority"
      MODEL_NAME = "ticket-priority"
      
      
      def setup():
          mlflow.set_tracking_uri(TRACKING_URI)
          mlflow.set_registry_uri(TRACKING_URI)
          if mlflow.get_experiment_by_name(EXPERIMENT) is None:
              mlflow.create_experiment(EXPERIMENT, artifact_location=ARTIFACTS)
          mlflow.set_experiment(EXPERIMENT)
      • The tracking URI starts with sqlite, so the "notebook" is one SQLite file, mlflow.db. Settings and scores go in there.
      • The artifacts folder, mlartifacts, is the shelf where saved models go.
      • setup() points MLflow at that file, creates the experiment ticket-priority if it isn't there yet, and selects it. An experiment is just the folder of runs that belong together.

      Both live in the project folder. No server to start, no account to make, and it all works offline. (The MLFLOW_STORE_DIR line only matters when the project runs in Docker; on your machine it falls back to the project folder.)

      train.py: each pass of the loop writes one run

      """Train the ticket model with three settings of C and log every run to MLflow."""
      import mlflow
      import mlflow.sklearn
      from sklearn.linear_model import LogisticRegression
      from sklearn.metrics import accuracy_score, f1_score
      
      import features
      import tracking
      
      tracking.setup()
      X_train, X_test, y_train, y_test = features.load()
      
      for c in (0.1, 1.0, 10.0):
          with mlflow.start_run(run_name=f"logreg-C{c}"):
              model = LogisticRegression(C=c, max_iter=1000)
              pipe = features.make_pipeline(model)
              pipe.fit(X_train, y_train)
              pred = pipe.predict(X_test)
              acc = accuracy_score(y_test, pred)
              f1 = f1_score(y_test, pred)
      
              mlflow.log_param("model", "LogisticRegression")
              mlflow.log_param("C", c)
              mlflow.log_metric("accuracy", acc)
              mlflow.log_metric("f1", f1)
              mlflow.sklearn.log_model(pipe, name="model")
              print(f"C={c:<5} accuracy={acc:.4f}  f1={f1:.4f}")

      For each value of C, with mlflow.start_run(...) opens a new run, named after the setting. Inside, it's the usual work: build, fit, predict, score. Then:

      • log_param writes the settings, the things you choose: the model name and C.
      • log_metric writes the scores, the things you measure: accuracy and F1.
      • mlflow.sklearn.log_model saves the model. When the with block ends, the run is closed and marked finished.

      The whole pipeline goes on the shelf

      pipe isn't only the logistic regression. features.make_pipeline builds a one-hot step for the three text columns (channel, customer_tier, product_area), passes the five number columns straight through, and then adds the model (see Pipelines and ColumnTransformer). So log_model saves the whole pipeline, under the name model.

      It lands in mlartifacts as five files: MLmodel (says what it is), conda.yaml and python_env.yaml (the environment), requirements.txt (the library versions) and model.skops, the fitted pipeline itself, about 102 KB. Because the one-hot step is inside, whoever loads it later doesn't need to rebuild anything.

      Run it

      python train.py
      C=0.1   accuracy=0.6800  f1=0.6396
      C=1.0   accuracy=0.6820  f1=0.6475
      C=10.0  accuracy=0.6840  f1=0.6504

      A warning from MLflow about the torch version may scroll by. It's only about library versions and it's harmless. Saving a model takes a few seconds, so each run took around 17 to 25 seconds here. The project folder now has two new things: mlflow.db and mlartifacts/. The scores are on screen, and the record is in the database.

      Compare the runs in the MLflow UI

      mlflow ui --backend-store-uri sqlite:///mlflow.db

      Open http://127.0.0.1:5000 and you'll see three runs, newest first. The metric columns are optional, so open Columns and tick accuracy, f1 and C. Now the table is a comparison. Sort it by F1:

      MLflow 3.17.2 Runs page for the ticket-priority experiment, sorted by f1. Three runs: logreg-C10.0 with duration 17.3s, accuracy 0.684, f1 0.65044247; logreg-C1.0 with 16.8s, 0.682, 0.64745011; logreg-C0.1 with 24.8s, 0.68, 0.63963963.
      The three runs sorted by F1 in the MLflow UI. C = 10 is on top, but only just.

      logreg-C10.0 comes out on top at 0.6504. But look at the gap between best and worst: only 0.0108.

      A few more views are worth knowing. The chart view draws a bar per run; the bars start at zero so they look almost the same, which is why you read the numbers and not only the bars. Tick runs and click Compare to plot C against F1. Click a run's name to see its two params, two metrics, its status and duration, and an Artifacts tab with the five model files. The logged model also has its own page under Models, which says it isn't registered yet.

      Is a gap of 0.0108 real?

      It's easy to fool yourself here, so let's check. The same 2,000 tickets were split 20 other ways (seeds 0 to 19), and all three settings were trained every time.

      • The F1 for one setting moved from about 0.57 to about 0.68, just by changing the split.
      • Within any single split, the three settings differed by at most 0.0162.
      • C = 10 was best, or tied for best, in 13 of the 20 splits.

      So the split moves the score much more than C does. C = 10 isn't a bad choice, but a small gap is a note, not a verdict. That's exactly why you keep the record.

      Register the best run

      """Find the run with the best f1 and register its model as 'ticket-priority'."""
      import mlflow
      
      import tracking
      
      tracking.setup()
      runs = mlflow.search_runs(
          experiment_names=[tracking.EXPERIMENT],
          order_by=["metrics.f1 DESC"],
      )
      best = runs.iloc[0]
      name = best["tags.mlflow.runName"]
      c, f1 = best["params.C"], best["metrics.f1"]
      print(f"best run: {name}  C={c}  f1={f1:.4f}")
      
      uri = f"runs:/{best['run_id']}/model"
      result = mlflow.register_model(uri, tracking.MODEL_NAME)
      print(f"registered '{result.name}' as version {result.version}")
      best run: logreg-C10.0  C=10.0  f1=0.6504
      registered 'ticket-priority' as version 1

      search_runs returns the experiment's runs as a table, ordered by F1, highest first. The first row is the best run. register_model takes the address of that run's model and a name, and creates version 1. A warning line may appear here too; it's harmless.

      MLflow registry page for ticket-priority Version 1, showing Source Run logreg-C10.0, Source Model model, Aliases Add, and Stage (deprecated) None.
      Version 1 remembers where it came from: its source run is logreg-C10.0.

      Version 1 still knows which run made it, so its settings and score are one click away.

      Load it by name and version

      """Load a registered model by name and version, then predict two tickets."""
      import sys
      
      import mlflow.sklearn
      import pandas as pd
      
      import tracking
      
      tracking.setup()
      version = sys.argv[1] if len(sys.argv) > 1 else "1"
      uri = f"models:/{tracking.MODEL_NAME}/{version}"
      model = mlflow.sklearn.load_model(uri)
      
      tickets = pd.DataFrame([
          {"channel": "phone", "customer_tier": "enterprise",
           "product_area": "billing", "words": 140, "has_attachment": 1,
           "previous_tickets": 6, "hour": 23, "sentiment": -0.8},
          {"channel": "email", "customer_tier": "free",
           "product_area": "login", "words": 20, "has_attachment": 0,
           "previous_tickets": 0, "hour": 10, "sentiment": 0.6},
      ])
      proba = model.predict_proba(tickets)[:, 1]
      for row, p in zip(tickets.itertuples(), proba):
          label = "high" if p >= 0.5 else "low"
          name = f"{row.channel}/{row.customer_tier}/{row.product_area}"
          print(f"{name}: {label} (p_high={p:.3f})")
      phone/enterprise/billing: high (p_high=0.985)
      email/free/login: low (p_high=0.149)

      Look at the address: models:/ticket-priority/1. No run ID in the code, no C. Only a name and a version. That one line loads the whole pipeline, one-hot step included. Pass a different number to the script and you get a different version. The loading code never changes; the version number says which model.

      Hard-coding that number has a cost, though: a new model means editing code. The next article swaps the number for a movable label: Model Registry Aliases, the Champion and Rollback.

      Common mistakes

      • Logging the score but not the settings. A metric without its params can't be repeated. Log both in the same run.
      • Saving only the estimator. Log the whole pipeline, or the loader has to rebuild the one-hot step by hand.
      • Crowning a winner on a tiny gap. 0.0108 was smaller than the swing from one split to another. Re-split before you believe it.
      • Panicking at the warnings. The torch version warning and the registration warning are informational.

      Recap

      CallWhat it recordsIn this project
      log_paramsettings you choosemodel, C
      log_metricscores you measureaccuracy, f1
      mlflow.sklearn.log_modelthe whole fitted pipelinefive files, model.skops about 102 KB
      search_runs + register_modelthe best run, as a named versionticket-priority version 1 (C = 10, F1 0.6504)
      models:/name/versionload by name, not run IDmodels:/ticket-priority/1

      Try it yourself

      Add mlflow.log_param("max_iter", 1000) to train.py and run it again. Find max_iter in the Columns list, run register_best.py again, and load the new version with python load_and_predict.py 2.

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

      Join free on Skool →
      ← Previous
      MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      Next →
      MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      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 lab notebook, not loose notes
      • tracking.py: where MLflow keeps everything
      • train.py: each pass of the loop writes one run
      • The whole pipeline goes on the shelf
      • Run it
      • Compare the runs in the MLflow UI
      • Is a gap of 0.0108 real?
      • Register the best run
      • Load it by name and version
      • 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.