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
- Make a virtual environment:
python3 -m venv ~/mlops-lab && . ~/mlops-lab/bin/activate. pip install mlflow scikit-learn pandas.
Taken
Vink een taak aan als hij klaar is. Alleen je browser onthoudt dit.
- Start an MLflow server with a SQLite backend store and a local artifact folder on port 5000.
- Write
train.py: load the scikit-learn wine data set, split train/test with a fixedrandom_state, train aRandomForestClassifier, and log the parameters, the accuracy and F1 score, and the model (with a signature and an input example) to the experimentwine. - Run it three times with different
n_estimators/max_depthvalues (command-line arguments). - Compare the runs in the UI and with
mlflow.search_runs()sorted by F1. - Register the best run's model as
wine-classifierand set the alias **champion** on that version. - Serve
models:/wine-classifier@championon port 5001 and send a prediction withcurl. - (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
championis 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")andmlflow.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
- 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 - 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)) - 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 - 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 - 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]} - Optional image:
mlflow models build-docker -m "models:/wine-classifier@champion" -n wine-api:1anddocker run -p 5001:8080 wine-api:1.
Mijn notities
Nog geen notities.