Zum Inhalt springen

Lektion 24 · Projects and Reference

Project: A Tracked Model Release

Build an end-to-end MLflow project: track a parameter search, choose a model by a written rule, register it, gate the release and plan a rollback.

In this project you connect the main pieces of classic tracking: runs, a search, evaluation, a registry and an alias. First you build the logic with a stand-in, then you apply it with real MLflow on your computer.

The task

Classify flowers by species with the iris dataset from scikit-learn. It is small, so it runs quickly. The process matters more than the score.

Rules you decide first:

  • Primary metric: validation F1 (macro average).
  • Guardrail: tree depth at most 5, so the tree stays readable.
  • Tie-breaker: the smaller depth.
  • Release gate: test F1 of at least 0.85.

Step 1: practice the logic

The stand-in uses a made-up score table in place of training.

Python Stand-in: search, select, gate and release

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Depth 8 has the best validation score but breaks the guardrail. Depths 3 and 5 tie, so the smaller one wins.

Step 2: the real version

Save this as train.py and run it on your computer.

Python
import mlflow
from mlflow import MlflowClient
from sklearn.datasets import load_iris
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("iris-release")

X, y = load_iris(return_X_y=True, as_frame=True)
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(
    X_dev, y_dev, test_size=0.25, random_state=0, stratify=y_dev)

candidates = []
with mlflow.start_run(run_name="depth-search"):
    mlflow.log_params({"depths": "1,2,3,5,8", "seed": 0})
    for depth in [1, 2, 3, 5, 8]:
        with mlflow.start_run(run_name=f"depth-{depth}", nested=True):
            model = DecisionTreeClassifier(max_depth=depth, random_state=0)
            model.fit(X_train, y_train)
            val = f1_score(y_val, model.predict(X_val), average="macro")
            mlflow.log_param("max_depth", depth)
            mlflow.log_metric("val_f1", val)
            info = mlflow.sklearn.log_model(
                model, name="model", input_example=X_train.head(3),
                # we trained this tree ourselves, so we trust its type
                skops_trusted_types=["sklearn.tree._tree.Tree"])
            if depth <= 5:
                candidates.append((-val, depth, model, info.model_uri))

    _, depth, model, uri = min(candidates, key=lambda c: c[:2])
    test = f1_score(y_test, model.predict(X_test), average="macro")
    mlflow.log_metrics({"chosen_depth": depth, "test_f1": test})

if test >= 0.85:
    version = mlflow.register_model(uri, "iris-classifier").version
    MlflowClient().set_registered_model_alias("iris-classifier", "champion", version)
    print("Released version", version)
else:
    print("Gate failed with", round(test, 3))

We do not show expected numbers, because they can depend on library versions.

Step 3: use and inspect it

Python
champion = mlflow.pyfunc.load_model("models:/iris-classifier@champion")
print(champion.predict(X_test.head(5)))

Start the UI with mlflow server --backend-store-uri sqlite:///mlflow.db and check:

  1. The parent run and its five children.
  2. The signature of a logged model.
  3. The registered version and its link to the source.

Extensions

  • Add a dataset input and a confusion matrix plot.
  • Use mlflow.models.evaluate with a threshold instead of the manual check.
  • Repeat with three seeds and report the spread, as in comparing runs.
  • Serve the champion with mlflow models serve and call it.
  • Write a rollback script that moves the alias to the previous version.

Ask a friend to run your project from a clean folder. Wherever they get stuck, your instructions or your pinned requirements need work.

A common mistake

If the gate fails, do not try more depths until the test score passes. That tunes against the test set. Go back to the training and validation data, and use fresh test data for the next release decision if you can.

Write the project note

Finish by writing a one-page note and logging it as an artifact on the parent run. Include:

  • The goal and the data source.
  • How you split the data, and the seed.
  • The selection rule and the release gate.
  • The chosen model, with validation and test results.
  • Known limits, such as the small size of the dataset.
  • How to roll back.

The iris dataset is tiny, so scores can move a lot with a different split. Say this plainly in your note. Honest limits are a sign of good work, not of weakness.

Check your work against these questions

Question Where to look
Can you find the settings of the chosen model? The child run
Does the registered version link back to it? The registry
Does the model have a signature? The model page
Is the test score logged once for the chosen model? The parent run
Could you move the alias back? Your rollback script

If any answer is "no", improve the script before you move on.

Make it automatic

As a final challenge, turn the script into a pipeline step. Let it exit with an error when the gate fails, so that a continuous integration job stops. Pass the tracking address through the MLFLOW_TRACKING_URI environment variable, and keep the pinned requirements next to the script. Add a small test that loads the champion and predicts on three rows. When this runs from a clean checkout on another machine, you have a release process that others can trust and repeat.

What you practiced

You wrote rules before looking at results. You tracked every trial, kept the test set out of the choice, recorded lineage, and made release a deliberate step. These habits transfer to larger datasets, other libraries and bigger teams. Only the training code changes.

Share your result

Show your project to someone else: the code, the written rules, the run history and the note. Ask them to explain which model is live and why. If they can do that from your records alone, your tracking works. If they need to ask you, note what was missing and add it. This is the most honest test of any tracking setup, and it takes only a few minutes.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. In the stand-in, why was depth 8 not chosen despite its higher validation score?

    The rule excluded depths above 5 before comparing scores.
  2. 2. How is the test set used in this project?

    Selection uses validation data, and the test set checks the final choice.
  3. 3. What does the champion alias give a program that loads the model?

    The program keeps using the alias while you control which version it points to.

Summary

  • Write selection and release rules before training.
  • Track every trial, then check only the winner on test data.
  • Register and set the alias only after the gate passes.
  • Plan rollback and let someone else reproduce your work.

Next: Project: Trace and Evaluate a Support Bot

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.