Deploying AI Models with Docker and Kubernetes / Start Here

Meet the practice model

Lesson 3 of 29. Open to read. No account needed.

What You Will Do

Every later lesson deploys the same model, so this lesson makes it and looks inside it. You will create the project folder the whole course uses, install the pinned Python packages into a virtual environment, run the supplied training script, and then open the saved file to see exactly what a serving system has to carry around: not just "the model", but a specific object that only works with specific library versions. You will also score a small file of readings with it, which is the batch job you will later run on the cluster.

You do not need to understand the training. The script is supplied, it runs in under two minutes, and the course never changes it. What matters for deployment is what comes out.

The Model and Its Story

The practice model predicts whether a machine needs service from six sensor readings: temperature, vibration, pressure, hours since the last service, load and ambient temperature. The data is synthetic: scikit-learn's make_classification generates 8,000 rows with a fixed random seed, so every learner gets the same numbers, no real customer data is involved, and the lesson can name the exact accuracy you should see. The feature names are a story laid over generated columns; the model does not know what a "temperature" is.

The script trains two models from the same data:

  • The small model: a pipeline of a StandardScaler (which puts every feature on the same scale) and a LogisticRegression. It is about 1.6 KB and loads in a few milliseconds. This is the one the API serves.
  • The large model: the same scaler followed by a RandomForestClassifier with 600 trees. It is about 33 MB and takes a noticeable fraction of a second to load. It is more accurate, and it exists so that later lessons have a realistically sized artifact when they discuss image size, startup time and where a model file should live.

Both are saved with joblib, the persistence library scikit-learn recommends for its models. Each file holds a Python dictionary, which the course calls the bundle: the fitted pipeline, the list of feature names in the order the model expects, and a version string. The version is the course's own label (1.0.0), not anything scikit-learn knows about; the release lessons change it to 2.0.0 to tell versions apart.

What a Saved Model Really Is

A joblib file is a serialised Python object, written with pickle underneath. Two consequences follow, and both shape the rest of the course.

It is code, not data. Loading a pickle can run arbitrary code. Never load a model file from a source you do not trust, and treat model files in production with the same care as an executable. The course's files are made by your own copy of the script.

It is tied to its library versions. scikit-learn supports loading a model only with the same version that saved it. A different version may appear to load, then predict wrongly or crash, and it emits an InconsistentVersionWarning when it notices. So the environment that serves the model must install the same scikit-learn, and the same NumPy and SciPy it depends on, as the one that trained it. This is the single strongest argument for the course's exact version pins: the requirements.txt you install here is the one the Dockerfile installs later, line for line.

scikit-learn's documentation also recommends recording, next to the model, the training code, the data snapshot, the library versions and a validation score, so the model can be rebuilt. The bundle's version, the fixed random seed and the printed accuracy are the course's small version of that practice.

Exercise: Train and Inspect the Model

Goal: create the project folder and virtual environment, train both models, inspect the bundle and score a file of readings.

Starting state: the toolchain lesson is done; python3 --version prints 3.12 to 3.14; internet access to download the Python packages (about 150 MB). The folder ~/ai-deploy-practice/aim-api should not exist yet.

  1. Create the project folder and the virtual environment:

    mkdir -p ~/ai-deploy-practice/aim-api
    cd ~/ai-deploy-practice/aim-api
    python3 -m venv .venv
    .venv/bin/python --version
    

    A virtual environment is a private copy of Python's package folder, so the course's pins cannot disturb other projects on your computer. The course calls the environment's own interpreter directly, .venv/bin/python and .venv/bin/pip, rather than activating it, so that every command works the same way in any shell. The version printed must be 3.12 to 3.14.

  2. Write the pinned requirements and install them. The block below writes the file with a here document; copy it whole:

    cat > requirements.txt <<'EOF'
    fastapi==0.156.8
    uvicorn==0.54.0
    scikit-learn==1.9.1
    joblib==1.6.0
    numpy==2.5.4
    scipy==1.18.1
    threadpoolctl==3.7.0
    prometheus_client==0.26.0
    EOF
    .venv/bin/pip install -r requirements.txt
    

    Every line pins an exact version with ==. FastAPI, uvicorn and the Prometheus client are for the API lessons; scikit-learn, joblib, NumPy, SciPy and threadpoolctl are the model's own dependencies. The install takes a minute or two and ends with a "Successfully installed" line listing these and a few packages they pull in.

  3. Write the training script, the inspection script and the batch scorer. Copy each block whole:

    cat > train.py <<'EOF'
    """Train the practice models from synthetic data (lesson meet-the-practice-model).
    
    Writes models/model.joblib (small pipeline) and models/model-large.joblib (larger ensemble)
    and prints held-out accuracy, file sizes and load times.
    """
    import json
    import os
    import time
    
    import joblib
    from sklearn.datasets import make_classification
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import train_test_split
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import StandardScaler
    
    FEATURES = ["temperature_c", "vibration_mm_s", "pressure_kpa", "runtime_hours", "load_percent", "ambient_c"]
    X, y = make_classification(n_samples=8000, n_features=6, n_informative=4, n_redundant=1, n_clusters_per_class=2, class_sep=1.1, random_state=42)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
    
    small = Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression(max_iter=1000))]).fit(X_train, y_train)
    large = Pipeline([("scale", StandardScaler()), ("clf", RandomForestClassifier(n_estimators=600, random_state=42, n_jobs=-1))]).fit(X_train, y_train)
    
    os.makedirs("models", exist_ok=True)
    joblib.dump({"pipeline": small, "features": FEATURES, "version": "1.0.0"}, "models/model.joblib")
    joblib.dump({"pipeline": large, "features": FEATURES, "version": "1.0.0-large"}, "models/model-large.joblib")
    
    report = {"small_accuracy": round(float(small.score(X_test, y_test)), 4), "large_accuracy": round(float(large.score(X_test, y_test)), 4)}
    for name in ["model.joblib", "model-large.joblib"]:
        path = f"models/{name}"
        started = time.perf_counter()
        joblib.load(path)
        report[f"{name}_load_s"] = round(time.perf_counter() - started, 3)
        report[f"{name}_bytes"] = os.path.getsize(path)
    print(json.dumps(report, indent=1))
    EOF
    cat > inspect_model.py <<'EOF'
    """Open the saved bundle and print what serving needs to know about it."""
    import platform
    import sys
    
    import joblib
    import sklearn
    
    bundle = joblib.load(sys.argv[1] if len(sys.argv) > 1 else "models/model.joblib")
    print("keys:", sorted(bundle))
    print("version:", bundle["version"])
    print("features:", bundle["features"])
    print("pipeline steps:", [name for name, _ in bundle["pipeline"].steps])
    print("saved with scikit-learn:", getattr(bundle["pipeline"], "_sklearn_version", "unknown"), "| running:", sklearn.__version__)
    print("python:", platform.python_version())
    EOF
    mkdir -p app
    : > app/__init__.py
    cat > app/batch.py <<'EOF'
    """Batch scoring: read CSV rows from a path, write predictions as CSV to stdout (used from the Jobs lesson on)."""
    import csv
    import os
    import sys
    
    import joblib
    import numpy as np
    
    bundle = joblib.load(os.environ.get("MODEL_PATH", "models/model.joblib"))
    rows = list(csv.DictReader(open(sys.argv[1])))
    matrix = np.array([[float(row[name]) for name in bundle["features"]] for row in rows])
    probabilities = bundle["pipeline"].predict_proba(matrix)[:, 1]
    writer = csv.writer(sys.stdout)
    writer.writerow(["row", "needs_service", "probability", "model_version"])
    for index, probability in enumerate(probabilities):
        writer.writerow([index, int(probability >= 0.5), f"{probability:.4f}", bundle["version"]])
    print(f"scored {len(rows)} rows", file=sys.stderr)
    EOF
    cat > readings.csv <<'EOF'
    temperature_c,vibration_mm_s,pressure_kpa,runtime_hours,load_percent,ambient_c
    71.5,4.2,310,12000,82,24
    40.0,0.8,290,300,35,21
    95.2,9.9,350,30000,97,33
    EOF
    ls -R
    

    app/ is a Python package (the empty __init__.py makes it one) that the API lessons fill in; the batch scorer lives there from the start so that the same package later goes into the image.

  4. Train:

    .venv/bin/python train.py
    ls -l models
    

    Illustrative output (the random seed fixes the numbers, so your accuracies should match to the last digit; sizes may differ by a few bytes and the load times depend on your computer):

    {
     "small_accuracy": 0.775,
     "large_accuracy": 0.9431,
     "model.joblib_load_s": 0.02,
     "model.joblib_bytes": 1646,
     "model-large.joblib_load_s": 0.283,
     "model-large.joblib_bytes": 32667477
    }
    

    Two numbers to keep: the small model is about 1.6 KB and loads in 20 ms; the large one is about 33 MB and loads in a quarter of a second here. A real model can be gigabytes and take minutes; the ratio between "copy a file" and "wait for it to load" is what the probes and storage lessons are about.

  5. Inspect the bundle:

    .venv/bin/python inspect_model.py
    .venv/bin/python inspect_model.py models/model-large.joblib
    

    Illustrative output for the small model:

    keys: ['features', 'pipeline', 'version']
    version: 1.0.0
    features: ['temperature_c', 'vibration_mm_s', 'pressure_kpa', 'runtime_hours', 'load_percent', 'ambient_c']
    pipeline steps: ['scale', 'clf']
    saved with scikit-learn: 1.9.1 | running: 1.9.1
    python: 3.13.0
    

    The features list is the contract between the model and anything that calls it: the API will build its input row in exactly this order. The two scikit-learn versions match because the same environment saved and loaded the file; that line is the one that would warn you in a mismatched environment.

  6. Score the readings file in batch:

    .venv/bin/python -m app.batch readings.csv
    

    Illustrative output:

    row,needs_service,probability,model_version
    0,1,1.0000,1.0.0
    1,1,1.0000,1.0.0
    2,1,1.0000,1.0.0
    scored 3 rows
    

    The CSV lines go to standard output and the "scored" line to standard error, so the predictions can be redirected to a file without the note. The synthetic model predicts "needs service" for all three sample rows with a probability that rounds to 1.0; that is a property of the generated data, not a bug. The later lessons use this script unchanged inside a container and then inside a Kubernetes Job.

Success: the two model files exist with the sizes above, the accuracies match, inspect_model.py shows version 1.0.0 and matching scikit-learn versions, and the batch scorer prints one row per reading.

If something differs:

What you seeLikely causeNext step
python3 -m venv fails with ensurepip is not available (Debian or Ubuntu)The venv module is a separate packageInstall python3-venv with your package manager, then retry
pip install reports no matching distribution for a pinPython outside 3.12 to 3.14, or an unsupported platform.venv/bin/python --version; use a supported Python and recreate the venv
ModuleNotFoundError: No module named 'sklearn'You ran the system python3 instead of the venv'sUse .venv/bin/python
Accuracies differ from the lessonA different scikit-learn version, or an edited scriptCheck pip show scikit-learn; compare the script with the block above
InconsistentVersionWarning when loadingThe file was saved under another scikit-learn versionRetrain with train.py in this environment; never serve a file that warns
Training takes several minutesThe random forest uses every core; a slow or busy machineWait; the result is the same
FileNotFoundError: models/model.joblibRunning from another foldercd ~/ai-deploy-practice/aim-api first

Independent task: before running anything, predict what inspect_model.py prints for models/model-large.joblib in the version and pipeline steps lines, then run it and compare. Then open train.py and find the one argument you would change to make the large model smaller but less accurate; do not change the file, since every later lesson relies on these exact outputs.

Cleanup: nothing to remove. The folder, the virtual environment and the models are the inputs to the API lessons. To start over, delete the folder with rm -rf ~/ai-deploy-practice/aim-api after checking the path and repeat this exercise.

Check Your Understanding

  1. Why does the course pin scikit-learn to an exact version both here and in the container image?
  2. A teammate sends you model.joblib by chat and asks you to serve it. What two questions do you ask before loading it?
  3. What is in the bundle besides the fitted model, and why does the API need each part?
  4. Why does the script save a second, larger model that the API never serves?

Answer and Reasoning

Independent task

The large bundle prints version: 1.0.0-large and the same two steps, ['scale', 'clf']: the pipeline shape is identical, only the classifier inside clf differs. The argument is n_estimators=600 on the RandomForestClassifier; fewer trees means a smaller file and a faster load, usually at some cost in accuracy. The course keeps 600 so that every learner's file sizes and timings match the lessons.

Understanding check

  1. scikit-learn supports loading a model only with the version that saved it. Pinning both environments to the same version is what makes the trained file and the serving image agree; the same reasoning applies to NumPy and SciPy, which the model objects contain.
  2. Where did it come from, and which scikit-learn (and Python) saved it. The first is a safety question, because loading a pickle runs code; the second decides whether it can be loaded correctly at all.
  3. The feature names, so the API builds its input row in the right order, and the version string, so the API can report which model answered. The fitted pipeline alone would predict, but the caller could not tell what it expects or which release it is.
  4. To give later lessons a realistically sized artifact. Image size, startup time, probes, and where a model file lives all look trivial with a 1.6 KB file; the 33 MB file makes those trade-offs visible without needing a GPU or a long download.

References

24 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy