πŸ€– AI/ML

Optuna

Optuna

An automatic hyperparameter optimization framework. Bayesian optimization.

πŸ“– Detailed Explanation

Optuna is an open-source framework that automatically optimizes the hyperparameters of machine learning and deep learning models. It efficiently searches for the optimal combination of hyperparameters that affect model performance, such as the learning rate, number of layers, and batch size.

Optuna was developed in 2018 by Preferred Networks in Japan. To improve on the inefficiency of existing Grid Search and Random Search, it adopted the TPE (Tree-structured Parzen Estimator) algorithm, which is based on Bayesian optimization, as its core.

The core principle is the "Define-by-Run" approach. Instead of defining the search space in advance, it samples hyperparameters dynamically during code execution. It improves efficiency through Bayesian optimization, which learns from the results of previous trials and focuses its search on more promising regions.

In practice, it greatly reduces model tuning time. The Pruning feature stops low-performing trials early, and the Dashboard can visualize the optimization process, which is also useful for experiment management.

πŸ’» Code Example

# Optuna ν•˜μ΄νΌνŒŒλΌλ―Έν„° μ΅œμ ν™” 예제
import optuna
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier

# 데이터 λ‘œλ“œ
iris = load_iris()
X, y = iris.data, iris.target

# λͺ©μ  ν•¨μˆ˜ μ •μ˜ (μ΅œμ ν™” λŒ€μƒ)
def objective(trial):
    # ν•˜μ΄νΌνŒŒλΌλ―Έν„° 탐색 곡간 μ •μ˜ (Define-by-Run)
    n_estimators = trial.suggest_int("n_estimators", 10, 200)
    max_depth = trial.suggest_int("max_depth", 2, 32)
    min_samples_split = trial.suggest_float("min_samples_split", 0.1, 1.0)
    min_samples_leaf = trial.suggest_int("min_samples_leaf", 1, 10)

    # λͺ¨λΈ 생성 및 평가
    clf = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        min_samples_split=min_samples_split,
        min_samples_leaf=min_samples_leaf,
        random_state=42
    )

    # ꡐ차 검증 점수 λ°˜ν™˜ (Optunaκ°€ μ΅œλŒ€ν™”ν•  κ°’)
    score = cross_val_score(clf, X, y, cv=5).mean()
    return score

# μŠ€ν„°λ”” 생성 및 μ΅œμ ν™” μ‹€ν–‰
study = optuna.create_study(direction="maximize")  # 정확도 μ΅œλŒ€ν™”
study.optimize(objective, n_trials=100)  # 100번 μ‹œλ„

# 졜적 κ²°κ³Ό 좜λ ₯
print(f"Best accuracy: {study.best_value:.4f}")
print(f"Best params: {study.best_params}")

# μ΅œμ ν™” κ³Όμ • μ‹œκ°ν™” (선택)
# optuna.visualization.plot_optimization_history(study)

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"We automated with Optuna a task that took 3 days with manual tuning and found the optimal hyperparameters in half a day. Accuracy also improved by 2%."
πŸ’¬ In an Interview
"Optuna's TPE algorithm is based on Bayesian optimization. It learns from the results of previous trials with a probabilistic model and first explores the hyperparameter combinations expected to perform well."
πŸ’¬ In a Technical Discussion
"Optuna's Pruning feature is the key. If you set up a MedianPruner, a trial is stopped early when its intermediate performance is lower than the median of the other trials, which can save more than 60% of GPU time."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Setting the search space too wide

Setting learning_rate in the range 1e-10 to 1 is inefficient. Use domain knowledge to narrow it to a reasonable range (e.g., 1e-5 to 1e-2).

❌
Setting the number of n_trials too low

It is difficult to find the optimum with 10 to 20 trials. We recommend at least 10 to 20 times as many trials as the number of hyperparameters.

βœ…
The right way

Enable Pruning, and store the study in a SQLite storage so that it can be resumed after an interruption. You can also use multiple GPUs through distributed optimization.

πŸ”— Related Terms

πŸ“š Learn More