pythonintermediate

MLflow Experiment Tracking in Python

Track ML experiments, log metrics, parameters, and artefacts with MLflow for reproducible training.

python
import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

mlflow.set_experiment('iris-classification')

with mlflow.start_run():
    params = {'n_estimators': 100, 'max_depth': 5, 'random_state': 42}
    mlflow.log_params(params)

    model = RandomForestClassifier(**params)
    model.fit(X_train, y_train)

    preds = model.predict(X_test)
    acc   = accuracy_score(y_test, preds)
    mlflow.log_metric('accuracy', acc)

    mlflow.sklearn.log_model(model, 'random_forest')
    print(f'Accuracy: {acc:.4f}')

Use Cases

  • experiment tracking
  • model versioning
  • ML reproducibility

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.