您可以使用 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)。