-
Notifications
You must be signed in to change notification settings - Fork 33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add multi-armed bandit sampler #155
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8f0c8b4
docs: multi-armed bandit.
ryota717 e18ea6a
feats: multi-armed bandit samplers.
ryota717 a1c1784
example: multi-armed bandit samplers.
ryota717 371556f
feat: select never selected arm for reward initialization.
ryota717 888441c
doc: fix POD.
ryota717 0bc6cb7
fix: rename module names.
ryota717 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 <Ryota Nishijima> | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
--- | ||
author: Ryota Nishijima | ||
title: MAB Epsilon-Greedy Sampler | ||
description: Sampler based on multi-armed bandit algorithm with epsilon-greedy arm selection. | ||
tags: [sampler, multi-armed bandit] | ||
optuna_versions: [4.0.0] | ||
license: MIT License | ||
--- | ||
|
||
## Class or Function Names | ||
|
||
- MABEpsilonGreedySampler | ||
|
||
## Example | ||
|
||
```python | ||
mod = optunahub.load_module("samplers/mab_epsilon_greedy") | ||
sampler = mod.MABEpsilonGreedySampler() | ||
``` | ||
|
||
See [`example.py`](https://github.com/optuna/optunahub-registry/blob/main/package/samplers/mab_epsilon_greedy/example.py) for more details. | ||
|
||
## Others | ||
|
||
This package provides a sampler based on Multi-armed bandit algorithm with epsilon-greedy selection. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
from .mab_epsilon_greedy import MABEpsilonGreedySampler | ||
|
||
|
||
__all__ = ["MABEpsilonGreedySampler"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import optuna | ||
import optunahub | ||
|
||
|
||
if __name__ == "__main__": | ||
module = optunahub.load_module( | ||
package="samplers/mab_epsilon_greedy", | ||
) | ||
sampler = module.MABEpsilonGreedySampler() | ||
|
||
def objective(trial: optuna.Trial) -> float: | ||
x = trial.suggest_categorical("arm_1", [1, 2, 3]) | ||
y = trial.suggest_categorical("arm_2", [1, 2]) | ||
|
||
return x + y | ||
|
||
study = optuna.create_study(sampler=sampler) | ||
study.optimize(objective, n_trials=20) | ||
|
||
print(study.best_trial.value, study.best_trial.params) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,70 @@ | ||||||
from collections import defaultdict | ||||||
from typing import Any | ||||||
from typing import Optional | ||||||
|
||||||
from optuna.distributions import BaseDistribution | ||||||
from optuna.samplers import RandomSampler | ||||||
from optuna.study import Study | ||||||
from optuna.study._study_direction import StudyDirection | ||||||
from optuna.trial import FrozenTrial | ||||||
from optuna.trial import TrialState | ||||||
|
||||||
|
||||||
class MABEpsilonGreedySampler(RandomSampler): | ||||||
"""Sampler based on Multi-armed Bandit Algorithm. | ||||||
|
||||||
Args: | ||||||
epsilon (float): | ||||||
Params for epsolon-greedy algorithm. | ||||||
epsilon is probability of selecting arm randomly. | ||||||
seed (int | None): | ||||||
Seed for random number generator and arm selection. | ||||||
|
||||||
""" | ||||||
|
||||||
def __init__( | ||||||
self, | ||||||
epsilon: float = 0.7, | ||||||
seed: Optional[int] = None, | ||||||
) -> None: | ||||||
super().__init__(seed) | ||||||
self._epsilon = epsilon | ||||||
|
||||||
def sample_independent( | ||||||
self, | ||||||
study: Study, | ||||||
trial: FrozenTrial, | ||||||
param_name: str, | ||||||
param_distribution: BaseDistribution, | ||||||
) -> Any: | ||||||
states = (TrialState.COMPLETE, TrialState.PRUNED) | ||||||
trials = study._get_trials(deepcopy=False, states=states, use_cache=True) | ||||||
|
||||||
rewards_by_choice: defaultdict = defaultdict(float) | ||||||
cnt_by_choice: defaultdict = defaultdict(int) | ||||||
for t in trials: | ||||||
rewards_by_choice[t.params[param_name]] += t.value | ||||||
cnt_by_choice[t.params[param_name]] += 1 | ||||||
|
||||||
# Use never selected arm for initialization like UCB1 algorithm. | ||||||
# ref. https://github.com/optuna/optunahub-registry/pull/155#discussion_r1780446062 | ||||||
never_selected = [ | ||||||
arm for arm in param_distribution.choices if arm not in rewards_by_choice | ||||||
] | ||||||
if never_selected: | ||||||
return self._rng.rng.choice(never_selected) | ||||||
|
||||||
# If all arms are selected at least once, select arm by epsilon-greedy. | ||||||
if self._rng.rng.rand() < self._epsilon: | ||||||
return self._rng.rng.choice(param_distribution.choices) | ||||||
else: | ||||||
if study.direction == StudyDirection.MINIMIZE: | ||||||
return min( | ||||||
param_distribution.choices, | ||||||
key=lambda x: rewards_by_choice[x] / max(cnt_by_choice[x], 1), | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nit]
Suggested change
|
||||||
) | ||||||
else: | ||||||
return max( | ||||||
param_distribution.choices, | ||||||
key=lambda x: rewards_by_choice[x] / max(cnt_by_choice[x], 1), | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nit]
Suggested change
|
||||||
) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nit]