LoginSignup
7
1

More than 1 year has passed since last update.

C++からOptunaを呼ぶライブラリを作った

Last updated at Posted at 2021-11-30

まとめ

これを書いた。 https://github.com/not522/optuna-cpp

Python以外の言語でOptunaを使う

OptunaはPythonのライブラリなので、他の言語で使うには

  1. Pythonから他の言語を呼び出す
  2. Optunaのcommand line interfaceを使う

のどちらかが必要です。optuna-cppでは2番目の方法を採用して、C++だけでOptunaを呼び出せるようにしています。

使い方

#include <iostream>

// optuna.hとnlohmann/json.hppのある環境でコンパイルしてください
#include "optuna.h"

int main() {
  // studyの作成
  optuna::Study study("sqlite:///example.db", "test_study", optuna::MINIMIZE, true);

  // 探索空間の定義
  optuna::SearchSpace search_space;
  search_space.add_categorical<std::string>("c", {"a", "b"});
  search_space.add_float("x", -10, 10);
  search_space.add_int("y", -10, 10);

  // trialを10回行う
  for (int i = 0; i < 10; ++i) {
    optuna::Trial trial = study.ask(search_space);
    std::string c = trial.param<std::string>("c");
    double x = trial.param<double>("x");
    int y = trial.param<int>("y");
    if (c == "a") {
      study.tell(trial, x * x + y * y);
    } else {
      study.tell(trial, x * x + y * y + 1);
    }
  }

  // 最適化履歴の取得
  for (const optuna::FrozenTrial &trial : study.trials()) {
    std::cout << trial.number << " "
              << trial.state << " "
              << trial.param<std::string>("c") << " "
              << trial.param<double>("x") << " "
              << trial.param<int>("y") << " "
              << trial.value << std::endl;
  }

  // best trialの取得
  const optuna::FrozenTrial best_trial = study.best_trial();
  std::cout << best_trial.number << " " << best_trial.value << std::endl;
}

Interface

Optuna CLIで最適化する場合、ask-and-tell interfaceを使うことになります。また、CLIではdefine-by-run形式は使えず、define-and-run形式になります。
Optuna本来のdefine-and-runの書き方だと少し冗長になるので、SearchSpaceというクラスを作ってadd_float/add_int/add_categoricalという関数で記述できるようにしました。

サポートできてないこと

  1. 多目的最適化
  2. デフォルト以外のSampler
  3. 枝刈り
  4. 分岐のある探索空間

多目的最適化とデフォルト以外のSamplerはCLIには存在するので、ちゃんと実装すれば対応できます。枝刈りや分岐のある探索空間はOptuna CLI側がまだ未対応なので、Optuna内部の実装が必要になります。

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1