Skip to content

Instantly share code, notes, and snippets.

@initcron
Created May 26, 2025 10:57
Show Gist options
  • Save initcron/3d235a7011bce71cddd62091561bed6f to your computer and use it in GitHub Desktop.
Save initcron/3d235a7011bce71cddd62091561bed6f to your computer and use it in GitHub Desktop.
import mlflow
from mlflow.models import infer_signature
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error

# 1. Set tracking URI to local MLflow server
mlflow.set_tracking_uri("http://host.docker.internal:5555")
print("📡 Tracking to:", mlflow.get_tracking_uri())

# 2. Set experiment name (create if not exists)
mlflow.set_experiment("simple-linear-demo")

# 3. Create and log a run
with mlflow.start_run():
    # Generate toy regression data
    X, y = make_regression(n_samples=100, n_features=1, noise=10, random_state=42)

    # Train model
    model = LinearRegression()
    model.fit(X, y)

    # Predict and evaluate
    y_pred = model.predict(X)
    mse = mean_squared_error(y, y_pred)

    # Infer model signature and input example
    signature = infer_signature(X, y_pred)
    input_example = X[:5]  # A small batch as sample input

    # Log parameters and metrics
    mlflow.log_param("model_type", "LinearRegression")
    mlflow.log_metric("mse", mse)

    # Log model with signature and example
    mlflow.sklearn.log_model(
        model,
        artifact_path="model",
        signature=signature,
        input_example=input_example
    )

    print(f"✅ Run logged with MSE: {mse:.2f}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment