Experiment tracking
5.10.5kata 5 de 5

Hyperparameter Search

Sweeps automáticos de hiperparámetros con MLflow y Optuna

La búsqueda manual de hiperparámetros (probar combinaciones a mano) no escala: con 5 hiperparámetros de 4 valores cada uno hay 1024 combinaciones posibles. El hyperparameter search automatizado delega este proceso a un algoritmo de optimización. Grid Search prueba exhaustivamente todas las combinaciones, Random Search prueba combinaciones aleatorias (sorprendentemente efectivo con 30-60 trials), y métodos bayesianos como Optuna aprenden de los resultados anteriores para proponer combinaciones más prometedoras.

Optuna es la librería de optimización de hiperparámetros más usada en el ecosistema Python. Define el espacio de búsqueda con funciones como `trial.suggest_float('lr', 1e-5, 1e-1, log=True)` o `trial.suggest_categorical('optimizer', ['adam', 'sgd'])`. Cada evaluación se llama 'trial'. Optuna usa el algoritmo TPE (Tree-structured Parzen Estimator) por defecto, que es un método bayesiano que modela la distribución de hiperparámetros buenos vs malos y sugiere valores con alta probabilidad de mejorar la métrica objetivo.

La integración entre Optuna y MLflow es natural: dentro de la función objetivo de Optuna se abre un run de MLflow, se loguean los hiperparámetros del trial actual, se entrena el modelo, se loguea la métrica, y se retorna el valor que Optuna debe optimizar. Al final del sweep, MLflow tiene registrados todos los trials con sus métricas, y Optuna tiene el análisis de importancia de hiperparámetros. Ambas herramientas se complementan: Optuna para optimización, MLflow para trazabilidad.

structure.txt
# Hyperparameter Search with Optuna + MLflow

# pip install optuna mlflow scikit-learn

import optuna
import mlflow
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
import numpy as np

# Generate sample data
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)

mlflow.set_experiment('optuna-rf-sweep')

def objective(trial):
    # Define search space
    n_estimators = trial.suggest_int('n_estimators', 50, 300)
    max_depth = trial.suggest_int('max_depth', 3, 15)
    min_samples_split = trial.suggest_int('min_samples_split', 2, 10)

    with mlflow.start_run(nested=True):
        # Log hyperparameters chosen by Optuna
        mlflow.log_params({
            'n_estimators': n_estimators,
            'max_depth': max_depth,
            'min_samples_split': min_samples_split,
        })

        model = RandomForestClassifier(
            n_estimators=n_estimators,
            max_depth=max_depth,
            min_samples_split=min_samples_split,
            random_state=42
        )
        score = cross_val_score(model, X, y, cv=3, scoring='accuracy').mean()

        mlflow.log_metric('cv_accuracy', score)

    return score  # Optuna maximizes this value

# Run the sweep with a parent run for context
with mlflow.start_run(run_name='optuna-sweep-parent'):
    study = optuna.create_study(direction='maximize')
    study.optimize(objective, n_trials=30)

    best = study.best_params
    mlflow.log_params({f'best_{k}': v for k, v in best.items()})
    mlflow.log_metric('best_cv_accuracy', study.best_value)

print(f'Best params: {study.best_params}')
print(f'Best accuracy: {study.best_value:.4f}')

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    I'm running an Optuna sweep with MLflow but all trials appear as separate top-level runs. I can't tell they belong to the same sweep. How do I group them?

  2. 02

    My Optuna sweep is taking too long. I set n_trials=500 but after 100 trials the accuracy improvement is negligible. How should I stop it intelligently?

  3. 03

    I finished an Optuna sweep and want to retrain the final model with the best hyperparameters and log it properly to MLflow. How?