注意
转至末尾 下载完整的示例代码。
(基于文件) 日志存储
Optuna 提供了 JournalStorage。通过此功能,您可以使用 NFS 作为共享存储,轻松地在网络上进行分布式优化,而无需设置 RDB 或 Redis。
import logging
import sys
import optuna
# Add stream handler of stdout to show the messages
optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
study_name = "example-study" # Unique identifier of the study.
file_path = "./optuna_journal_storage.log"
storage = optuna.storages.JournalStorage(
optuna.storages.journal.JournalFileBackend(file_path), # NFS path for distributed optimization
)
study = optuna.create_study(study_name=study_name, storage=storage)
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study.optimize(objective, n_trials=3)
A new study created in Journal with name: example-study
Trial 0 finished with value: 4.596235497552234 and parameters: {'x': -0.1438832751696708}. Best is trial 0 with value: 4.596235497552234.
Trial 1 finished with value: 18.936178621670795 and parameters: {'x': 6.3515719713306815}. Best is trial 0 with value: 4.596235497552234.
Trial 2 finished with value: 24.768028479300177 and parameters: {'x': -2.976748786034933}. Best is trial 0 with value: 4.596235497552234.
尽管此示例中的优化时间太短,无法并行运行,但您可以扩展此示例来编写一个可以并行运行的优化脚本。
注意
在 Windows 环境中,可能会出现“客户端未拥有必需的特权”的错误消息。在这种情况下,您可以通过指定 JournalFileOpenLock 来创建存储,从而解决问题。有关详细信息,请参阅 JournalStorage 的参考。
脚本总运行时间: (0 分 0.035 秒)