【问题标题】:Is there a way for Optuna `suggest_categorical`to return multiple choices from list?Optuna `suggest_categorical` 有没有办法从列表中返回多个选择?
【发布时间】:2023-01-01 14:24:49
【问题描述】:

我正在使用 Optuna 对我的模型进行超参数化。我有一个字段,我想在其中测试列表中的多个组合。例如:我有 ["lisa","adam","test"],我希望 suggest_categorical 返回的不仅仅是一个,而是一个随机组合:可能是["lisa", "adam"],可能是["adam"],可能是["lisa", "adam", "test"]。有没有办法通过内置的 Optuna 功能来实现这一点?

【问题讨论】:

    标签: python machine-learning hyperparameters optuna


    【解决方案1】:

    您可以使用 itertools.combinations 生成列表项的所有可能组合,然后将它们作为选项传递给 optuna 的 suggest_categorical

    import optuna
    import itertools
    import random
    import warnings
    warnings.filterwarnings('ignore')
    
    # generate the combinations
    iterable = ['lisa', 'adam', 'test']
    combinations = []
    for r in range(1, len(iterable) + 1):
        combinations.extend([list(x) for x in itertools.combinations(iterable=iterable, r=r)])
    print(combinations)
    # [['lisa'], ['adam'], ['test'], ['lisa', 'adam'], ['lisa', 'test'], ['adam', 'test'], ['lisa', 'adam', 'test']]
    
    # sample the combinations
    def objective(trial):
        combination = trial.suggest_categorical(name='combination', choices=combinations)
        return round(random.random(), 2)
    
    study = optuna.create_study()
    study.optimize(objective, n_trials=3)
    # [I 2022-08-18 08:03:51,658] A new study created in memory with name: no-name-3874ce95-2394-4526-bb19-0d9822d7e45c
    # [I 2022-08-18 08:03:51,659] Trial 0 finished with value: 0.94 and parameters: {'combination': ['adam']}. Best is trial 0 with value: 0.94.
    # [I 2022-08-18 08:03:51,660] Trial 1 finished with value: 0.87 and parameters: {'combination': ['lisa', 'test']}. Best is trial 1 with value: 0.87.
    # [I 2022-08-18 08:03:51,660] Trial 2 finished with value: 0.29 and parameters: {'combination': ['lisa', 'adam']}. Best is trial 2 with value: 0.29.
    

    在 optuna 的 suggest_categorical 中使用列表作为选项会引发警告消息,但显然这主要是无关紧要的(请参阅 optuna 的 GitHub 存储库中的 this issue)。

    【讨论】:

    • 谢谢 :) 我希望 optuna 已经实现了这个,但这也很好用。
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多