Geavanceerd
Zoeken inLabs
Zo zoek je
  • Zoek een taak of een tool (lvm, selinux, @podman); filter op niveau en op boek of cursus.
  • Met een leeg zoekvak toont een filter alleen al de labs — bijvoorbeeld alle moeilijke labs van één cursus.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Lab 3.1MLOps, Hoofdstuk 3

Track experiments in MLflow, register the best model and serve it as an API

Niveau
Gemiddeld
60 min
Machines
Linux or macOS with Python 3.10+ (mlflow, scikit-learn), optional Docker
Status
Nog niet begonnen

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

Doel

The engineer's view of machine learning: you do not need to invent the model, but you must make every training run repeatable and traceable. Run an MLflow tracking server with a database, train a small model with three settings, compare the runs, register the best one, give it the alias champion, and serve it as a REST API that a web app could call.

Voordat je begint

Taken

  1. Start an MLflow server with a SQLite backend store and a local artifact folder on port 5000.
  2. Write train.py: load the scikit-learn wine data set, split train/test with a fixed random_state, train a RandomForestClassifier, and log the parameters, the accuracy and F1 score, and the model (with a signature and an input example) to the experiment wine.
  3. Run it three times with different n_estimators / max_depth values (command-line arguments).
  4. Compare the runs in the UI and with mlflow.search_runs() sorted by F1.
  5. Register the best run's model as wine-classifier and set the alias **champion** on that version.
  6. Serve models:/wine-classifier@champion on port 5001 and send a prediction with curl.
  7. (Optional) Build a Docker image of the model with mlflow models build-docker.

Controleer je werk

curl -s localhost:5000/health; echo
python3 -c "import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); print(mlflow.search_runs(experiment_names=['wine'], order_by=['metrics.f1 DESC'])[['run_id','params.n_estimators','metrics.f1']].head(3))"
curl -s -X POST localhost:5001/invocations -H 'Content-Type: application/json' -d @sample.json
  • The server answers OK.
  • 3 runs, each with parameters, 2 metrics and a model artifact.
  • The model version with alias champion is the run with the best F1.
  • The prediction answer is like {"predictions": [0]}.

Hints

Toon de hints
  • Server: mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./mlruns --host 127.0.0.1 --port 5000.
  • mlflow.set_tracking_uri("http://localhost:5000") and mlflow.set_experiment("wine") at the start of the script.
  • infer_signature(X_test, model.predict(X_test)) makes the signature.
  • Aliases replace the old stages (Staging/Production): MlflowClient().set_registered_model_alias(name, "champion", version).
  • Serving: MLFLOW_TRACKING_URI=http://localhost:5000 mlflow models serve -m "models:/wine-classifier@champion" -p 5001 --env-manager local.

Oplossing

Toon de oplossing
  1. Start the server (keep this terminal open).
    mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./mlruns --host 127.0.0.1 --port 5000
  2. The training script.
    train.py
    import argparse
     
    import mlflow
    from mlflow.models import infer_signature
    from sklearn.datasets import load_wine
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import accuracy_score, f1_score
    from sklearn.model_selection import train_test_split
     
    p = argparse.ArgumentParser()
    p.add_argument("--n-estimators", type=int, default=100)
    p.add_argument("--max-depth", type=int, default=None)
    a = p.parse_args()
     
    mlflow.set_tracking_uri("http://localhost:5000")
    mlflow.set_experiment("wine")
    X, y = load_wine(return_X_y=True, as_frame=True)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
     
    with mlflow.start_run():
        model = RandomForestClassifier(n_estimators=a.n_estimators, max_depth=a.max_depth, random_state=42).fit(X_train, y_train)
        pred = model.predict(X_test)
        mlflow.log_params({"n_estimators": a.n_estimators, "max_depth": a.max_depth})
        mlflow.log_metrics({"accuracy": accuracy_score(y_test, pred), "f1": f1_score(y_test, pred, average="macro")})
        mlflow.sklearn.log_model(model, artifact_path="model", signature=infer_signature(X_test, pred), input_example=X_test.head(2))
  3. Three runs.
    python3 train.py --n-estimators 10 --max-depth 2
    python3 train.py --n-estimators 100 --max-depth 5
    python3 train.py --n-estimators 300
  4. Register the best run and set the alias.
    register.py
    import mlflow
    from mlflow import MlflowClient
     
    mlflow.set_tracking_uri("http://localhost:5000")
    best = mlflow.search_runs(experiment_names=["wine"], order_by=["metrics.f1 DESC"]).iloc[0]
    mv = mlflow.register_model(f"runs:/{best.run_id}/model", "wine-classifier")
    MlflowClient().set_registered_model_alias("wine-classifier", "champion", mv.version)
    print("champion = version", mv.version, "f1", best["metrics.f1"])
    python3 register.py
  5. Serve and call it.
    MLFLOW_TRACKING_URI=http://localhost:5000 mlflow models serve -m "models:/wine-classifier@champion" -p 5001 --env-manager local &
    python3 -c "from sklearn.datasets import load_wine; import json; X,_=load_wine(return_X_y=True, as_frame=True); print(json.dumps({'dataframe_split': X.head(1).to_dict(orient='split')}))" > sample.json
    curl -s -X POST localhost:5001/invocations -H 'Content-Type: application/json' -d @sample.json
    {"predictions": [0]}
  6. Optional image: mlflow models build-docker -m "models:/wine-classifier@champion" -n wine-api:1 and docker run -p 5001:8080 wine-api:1.

Mijn notities

Nog geen notities.

Lessen voor dit lab

Commando's in dit lab