注意
跳转到底部 下载完整的示例代码。
(基于文件的) 日志存储
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: 17.531687176572568 and parameters: {'x': 6.18708576178857}. Best is trial 0 with value: 17.531687176572568.
Trial 1 finished with value: 2.4905531135788244 and parameters: {'x': 3.5781486348182874}. Best is trial 1 with value: 2.4905531135788244.
Trial 2 finished with value: 30.991051799833517 and parameters: {'x': 7.566960732736806}. Best is trial 1 with value: 2.4905531135788244.
尽管本示例中的优化过程很短,不足以并行运行,但您可以扩展此示例来编写可以并行运行的优化脚本。
注意
在 Windows 环境中,可能会出现错误消息“客户端未持有所需的特权”。在这种情况下,您可以通过指定 JournalFileOpenLock
来创建存储以解决此问题。请参阅 JournalStorage
的参考文档了解任何详细信息。
脚本总运行时间: (0 分 0.036 秒)