How to Log Parameters in MLflow: Simple Guide
To log parameters in MLflow, use
mlflow.log_param(key, value) inside an active MLflow run. This records key-value pairs like hyperparameters so you can track them alongside your model and metrics.Syntax
The basic syntax to log a parameter in MLflow is mlflow.log_param(key, value).
- key: A string representing the parameter name.
- value: The parameter value, usually a string, int, or float.
- This function must be called inside an active MLflow run context.
python
import mlflow with mlflow.start_run(): mlflow.log_param("learning_rate", 0.01)
Example
This example shows how to start an MLflow run and log multiple parameters such as learning rate and number of trees. It demonstrates how parameters are saved for experiment tracking.
python
import mlflow with mlflow.start_run(): mlflow.log_param("learning_rate", 0.1) mlflow.log_param("num_trees", 100) print("Parameters logged successfully.")
Output
Parameters logged successfully.
Common Pitfalls
Common mistakes when logging parameters in MLflow include:
- Calling
mlflow.log_paramoutside an active run, which causes an error. - Logging non-serializable objects as parameter values.
- Using the same key multiple times in one run, which overwrites the previous value.
Always ensure you start a run with mlflow.start_run() before logging.
python
import mlflow # Wrong way: logging outside a run try: mlflow.log_param("batch_size", 32) except Exception as e: print(f"Error: {e}") # Right way: with mlflow.start_run(): mlflow.log_param("batch_size", 32) print("Logged batch_size inside run.")
Output
Error: No active run found. Please start a run before logging.
Logged batch_size inside run.
Quick Reference
| Function | Description | Example |
|---|---|---|
| mlflow.start_run() | Starts an MLflow run context | with mlflow.start_run(): |
| mlflow.log_param(key, value) | Logs a single parameter | mlflow.log_param('lr', 0.01) |
| mlflow.log_params(dict) | Logs multiple parameters at once | mlflow.log_params({'lr': 0.01, 'epochs': 10}) |
| mlflow.end_run() | Ends the active MLflow run | mlflow.end_run() |
Key Takeaways
Always log parameters inside an active MLflow run using mlflow.start_run().
Use mlflow.log_param(key, value) to record each parameter clearly.
Avoid logging complex objects; stick to simple types like strings, ints, or floats.
Repeated keys overwrite previous values within the same run.
Use mlflow.log_params() to log multiple parameters efficiently.