0
0
Ml-pythonHow-ToBeginner ยท 3 min read

How to Log Metrics in MLflow: Simple Guide with Examples

To log metrics in MLflow, use the mlflow.log_metric() function inside an active run context. This function records numeric values like accuracy or loss, which you can later view in the MLflow UI or retrieve programmatically.
๐Ÿ“

Syntax

The basic syntax to log a metric in MLflow is:

  • mlflow.log_metric(key, value, step=None)

Here, key is the name of the metric (a string), value is the numeric value to log, and step is an optional integer to indicate the step or epoch number.

You must call this inside an active MLflow run, which you start with mlflow.start_run().

python
import mlflow

with mlflow.start_run():
    mlflow.log_metric("accuracy", 0.95)
    mlflow.log_metric("loss", 0.1, step=1)
๐Ÿ’ป

Example

This example shows how to log multiple metrics during a simple training loop. It demonstrates starting a run, logging metrics with steps, and ending the run.

python
import mlflow
import time

with mlflow.start_run():
    for epoch in range(3):
        accuracy = 0.8 + epoch * 0.05
        loss = 0.5 / (epoch + 1)
        mlflow.log_metric("accuracy", accuracy, step=epoch)
        mlflow.log_metric("loss", loss, step=epoch)
        time.sleep(0.1)  # simulate training time

print("Metrics logged successfully.")
Output
Metrics logged successfully.
โš ๏ธ

Common Pitfalls

Common mistakes when logging metrics in MLflow include:

  • Calling mlflow.log_metric() outside an active run, which causes an error.
  • Using non-numeric values for metrics, which MLflow does not accept.
  • Not specifying step when logging metrics over epochs, making it hard to track progress.

Always ensure you have mlflow.start_run() active and use numeric values.

python
import mlflow

# Wrong way: logging metric outside a run
try:
    mlflow.log_metric("accuracy", 0.9)
except Exception as e:
    print(f"Error: {e}")

# Right way:
with mlflow.start_run():
    mlflow.log_metric("accuracy", 0.9)
    print("Metric logged inside run.")
Output
Error: No active run found. Please start a run before logging metrics. Metric logged inside run.
๐Ÿ“Š

Quick Reference

FunctionDescriptionParameters
mlflow.start_run()Starts an MLflow run contextNo parameters
mlflow.log_metric(key, value, step=None)Logs a numeric metrickey: metric name (str), value: metric value (float/int), step: optional step number (int)
mlflow.end_run()Ends the active MLflow runNo parameters (usually automatic with context manager)
โœ…

Key Takeaways

Always log metrics inside an active MLflow run using mlflow.start_run().
Use mlflow.log_metric() with a string key and numeric value to record metrics.
Optionally include a step number to track metrics over time or epochs.
Avoid logging metrics outside a run or using non-numeric values to prevent errors.
Use the MLflow UI to visualize logged metrics after running your code.