Open7
Optunaの探索方法の切り替え

基本的な話だが、もともとGridSearchをしていて、OptunaでデフォルトのTPEサンプラーを使うように変えた際に、思ったように性能が出ず、OptunaでもGridSearchがしたいとかいうケースでどうするのか確認した。

そもそもの話として、optuna.create_studyのサンプラーのデフォルトはoptuna.samplers.TPESamplerである。

GridSearchしたい場合は代わりにoptuna.samplers.GridSamplerを使う。
サンプルもついているのでGoogle Colabで実行してみると以下のようになる。
import optuna
def objective(trial):
x = trial.suggest_uniform('x', -100, 100)
y = trial.suggest_int('y', -100, 100)
return x ** 2 + y ** 2
search_space = {
'x': [-50, 0, 50],
'y': [-99, 0, 99]
}
study = optuna.create_study(sampler=optuna.samplers.GridSampler(search_space))
study.optimize(objective, n_trials=3*3)
ログは以下。
[I 2025-06-28 09:06:50,639] A new study created in memory with name: no-name-bb38df12-242c-4663-8e13-f18a162a9dde
/tmp/ipython-input-3-1895000139.py:4: FutureWarning: suggest_uniform has been deprecated in v3.0.0. This feature will be removed in v6.0.0. See https://github.com/optuna/optuna/releases/tag/v3.0.0. Use suggest_float instead.
x = trial.suggest_uniform('x', -100, 100)
[I 2025-06-28 09:06:50,641] Trial 0 finished with value: 2500.0 and parameters: {'x': 50.0, 'y': 0}. Best is trial 0 with value: 2500.0.
[I 2025-06-28 09:06:50,643] Trial 1 finished with value: 12301.0 and parameters: {'x': -50.0, 'y': 99}. Best is trial 0 with value: 2500.0.
[I 2025-06-28 09:06:50,645] Trial 2 finished with value: 2500.0 and parameters: {'x': -50.0, 'y': 0}. Best is trial 0 with value: 2500.0.
[I 2025-06-28 09:06:50,646] Trial 3 finished with value: 0.0 and parameters: {'x': 0.0, 'y': 0}. Best is trial 3 with value: 0.0.
[I 2025-06-28 09:06:50,648] Trial 4 finished with value: 12301.0 and parameters: {'x': 50.0, 'y': 99}. Best is trial 3 with value: 0.0.
[I 2025-06-28 09:06:50,650] Trial 5 finished with value: 12301.0 and parameters: {'x': 50.0, 'y': -99}. Best is trial 3 with value: 0.0.
[I 2025-06-28 09:06:50,651] Trial 6 finished with value: 9801.0 and parameters: {'x': 0.0, 'y': -99}. Best is trial 3 with value: 0.0.
[I 2025-06-28 09:06:50,653] Trial 7 finished with value: 12301.0 and parameters: {'x': -50.0, 'y': -99}. Best is trial 3 with value: 0.0.
[I 2025-06-28 09:06:50,655] Trial 8 finished with value: 9801.0 and parameters: {'x': 0.0, 'y': 99}. Best is trial 3 with value: 0.0.

optuna.samplers.GridSamplerにsearch_spaceで探索するグリッドを渡せばよさそう。

なお、CVをしたい場合はOptunaSearchCVを使うとよさそう。
ただしoptuna.create_studyとは異なるインターフェースを使うことになる。
以下の記事が大変分かりやすい。

optuna.create_studyを使う方法も紹介されている。

なお、sklearnのGridSearchCV