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

      CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push

      A small notes API, three pytest tests and one ci.yml: GitHub runs the tests on every push and pull request, builds the Docker image only if they pass, and shows a red or green check before anyone merges.

      Chaand Sheikh

      ·27 November 2026Pipelines, CI/CD and Cloud

      What you will learn

      • Explain continuous integration (CI) and what a red or green check means
      • Read a GitHub Actions workflow: on, jobs, steps, runs-on and uses
      • Make one job wait for another with needs, so the image is built only after the tests pass
      • Watch a broken change fail the tests and stop the build

      Before you start

      • Git and GitHub Fundamentals
      • Testing a FastAPI App with pytest
      • Containerising a Model API: A Dockerfile

      A teammate tidies up a helper function, tries it once, and pushes. The test that would've caught the bug was right there in the project, and nobody ran it. This happens on every team, and the fix fits in three words: every push, checked.

      We'll make GitHub test our code and build our Docker image automatically, every time we push. The project is a small notes API with one test file and one workflow file. Along the way you'll meet four things: a workflow, jobs, steps and checks.

      An inspector at the gate

      Think of a factory gate. The truck is your commit. At the gate, an inspector runs the same checklist on every truck. It doesn't get tired and it doesn't forget. Only after that does the truck get on the open road. In our world, that means only checked code gets merged.

      Continuous integration, CI for short, is the inspector. The workflow file is the checklist.

      Change, push, test, build, merge Change Push test pytest -q build docker build Merge on GitHub, a fresh machine, every push test fails: red cross, build never starts
      CI adds two automatic stops between the push and the merge.

      Three tests, one command

      First, what will the inspector check? tests/test_notes.py has three tests. The style is the same as in Testing a FastAPI App with pytest: a TestClient calls the app with no server running.

      import pytest
      from fastapi.testclient import TestClient
      
      from app.main import app, validate_note
      
      client = TestClient(app)
      
      
      def test_health_route():
          response = client.get("/health")
          assert response.status_code == 200
          assert response.json() == {"status": "ok"}
      
      
      def test_validate_note_trims_spaces():
          assert validate_note("  Buy milk  ") == "Buy milk"
      
      
      def test_validate_note_rejects_empty_title():
          with pytest.raises(ValueError):
              validate_note("   ")

      The first calls /health and expects 200 and ok. The second passes "Buy milk" with spaces around it and expects it back trimmed. The third checks that an empty title raises a ValueError. Here's the function they test, in app/main.py:

      def validate_note(title: str) -> str:
          """Trim the title and refuse an empty one."""
          title = title.strip()
          if not title:
              raise ValueError("title must not be empty")
          return title
      pytest -q
      ...                                                                      [100%]
      3 passed in 0.79s

      That's the exact command the inspector will run for us.

      ci.yml: when, and what

      The checklist is a plain text file, ci.yml, and it lives in .github/workflows/. GitHub finds it there by itself.

      name: CI
      
      on:
        push:
        pull_request:
      
      jobs:
        test:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - uses: actions/setup-python@v5
              with:
                python-version: "3.13"
            - name: Install dependencies
              run: pip install -r requirements-dev.txt
            - name: Run tests
              run: pytest -q
      
        build:
          needs: test
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - name: Build the image
              run: docker build -t notes-api:ci .
      • on says when to run: on every push and every pull request.
      • jobs holds two jobs, test and build.
      • runs-on: ubuntu-latest gives each job a fresh Ubuntu machine.
      • Steps run in order. The test job has four: check out the code, set up Python 3.13, install the packages, run pytest.
      • needs: test is the important line in build. Build starts only after the tests pass.
      • Steps that start with uses are ready-made actions, pinned to a major version (@v4, @v5) so an update doesn't surprise you. Steps with run are shell commands.

      A small helper script in the project, 01_show_workflow.py, reads the file and prints its shape:

      workflow: CI
      runs on : push, pull_request
      job test
        1. uses actions/checkout@v4
        2. uses actions/setup-python@v5
        3. run  pip install -r requirements-dev.txt
        4. run  pytest -q
      job build  (needs test)
        1. uses actions/checkout@v4
        2. run  docker build -t notes-api:ci .

      requirements-dev.txt pulls in the app's requirements plus the test tools:

      -r requirements.txt
      pytest==9.1.1
      httpx==0.28.1

      What happens on a push

      1. Your commit lands on GitHub.
      2. GitHub sees the push and starts a fresh machine, a clean one every time. Its docs call this a GitHub-hosted runner. That machine reads our workflow file.
      3. The test job runs first: pytest -q.
      4. If it passes, the build job runs docker build.
      5. At the end, a green check shows up on your pull request, so it's safe to merge.

      If any step fails, you get a red cross instead, and the later jobs don't even start. They're the same steps you'd run on your laptop. (The test and build outputs in this article come from running those same commands locally; GitHub Actions itself wasn't run for this lesson.) The difference is that they run on a clean machine, every time, without anyone asking.

      Break it

      Now the teammate's change, from broken/app/main.py. It still checks for an empty title, but look at the return:

      def validate_note(title: str) -> str:
          """Trim the title and refuse an empty one."""
          if not title.strip():
              raise ValueError("title must not be empty")
          return title

      It returns title as it came in, so the spaces never get trimmed. Same tests, new code:

      .F.                                                                      [100%]
      ================================== FAILURES ===================================
      _______________________ test_validate_note_trims_spaces _______________________
      
          def test_validate_note_trims_spaces():
      >       assert validate_note("  Buy milk  ") == "Buy milk"
      E       AssertionError: assert '  Buy milk  ' == 'Buy milk'
      E
      E         - Buy milk
      E         +   Buy milk
      E         ? ++        ++
      
      tests\test_notes.py:16: AssertionError
      =========================== short test summary info ===========================
      FAILED tests/test_notes.py::test_validate_note_trims_spaces - AssertionError:...
      1 failed, 2 passed in 1.28s

      One failed, two passed. We expected "Buy milk" and got it with the spaces still around it. On a pull request, this shows up as a red cross, and the build job never starts. The bug never reaches the customer.

      The build job

      The second job builds this Dockerfile:

      FROM python:3.13-slim
      WORKDIR /srv
      COPY requirements.txt .
      RUN pip install --no-cache-dir -r requirements.txt
      COPY app ./app
      EXPOSE 8000
      CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

      Requirements are copied and installed first, so Docker can reuse that layer when only the code changes, and the app folder goes in last because it changes most. (Containerising a model API walks through a Dockerfile like this line by line.) The build ends by naming the image:

      #10 naming to docker.io/library/notes-api:ci 0.0s done
      
      #10 unpacking to docker.io/library/notes-api:ci 1.0s done
      
      #10 DONE 3.5s

      If the tests pass, the code is correct. If the image builds too, it's shippable.

      Common mistakes

      • The file in the wrong folder. It has to be .github/workflows/, or GitHub never sees it.
      • Forgetting needs. Without it, jobs run side by side, and the image gets built even when the tests fail.
      • Test tools missing on the runner. The runner is empty. Anything pytest needs must be in requirements-dev.txt.
      • Unpinned actions. Pin uses to a version, so a new release doesn't change your checklist overnight.

      Recap

      WordMeaning
      WorkflowThe checklist, .github/workflows/ci.yml
      onWhen it runs: push, pull_request
      Job and stepsA job runs on a fresh machine; its steps run in order
      needsSets the order: build waits for test
      CheckRed cross or green check on the pull request, before merging

      Try it yourself: push the project to your own GitHub repository (see Git and GitHub fundamentals), break one assert on a branch, and open a pull request. Then fix it and watch the check turn green.

      Next, the same idea for the model itself: a quality gate in CI/CD.

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

      Join free on Skool →
      ← Previous
      Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      Next →
      CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      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
      • An inspector at the gate
      • Three tests, one command
      • ci.yml: when, and what
      • What happens on a push
      • Break it
      • The build job
      • Common mistakes
      • Recap
      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.