ray/rllib/contrib/bandits/examples/simple_context_bandit.py
Sven Mika 57544b1ff9
[RLlib] Examples folder restructuring (Model examples; final part). (#8278)
- This PR completes any previously missing PyTorch Model counterparts to TFModels in examples/models.
- It also makes sure, all example scripts in the rllib/examples folder are tested for both frameworks and learn the given task (this is often currently not checked) using a --as-test flag in connection with a --stop-reward.
2020-05-12 08:23:10 +02:00

58 lines
1.7 KiB
Python

"""A very simple contextual bandit example with 3 arms."""
import argparse
import gym
from gym.spaces import Discrete, Box
import numpy as np
import random
from ray import tune
from ray.rllib.utils.test_utils import check_learning_achieved
parser = argparse.ArgumentParser()
parser.add_argument("--run", type=str, default="contrib/LinUCB")
parser.add_argument("--as-test", action="store_true")
parser.add_argument("--stop-iters", type=int, default=200)
parser.add_argument("--stop-timesteps", type=int, default=100000)
parser.add_argument("--stop-reward", type=float, default=10.0)
class SimpleContextualBandit(gym.Env):
def __init__(self, config=None):
self.action_space = Discrete(3)
self.observation_space = Box(low=-1., high=1., shape=(2, ))
self.cur_context = None
def reset(self):
self.cur_context = random.choice([-1., 1.])
return np.array([self.cur_context, -self.cur_context])
def step(self, action):
rewards_for_context = {
-1.: [-10, 0, 10],
1.: [10, 0, -10],
}
reward = rewards_for_context[self.cur_context][action]
return (np.array([-self.cur_context, self.cur_context]), reward, True,
{
"regret": 10 - reward
})
if __name__ == "__main__":
args = parser.parse_args()
stop = {
"training_iteration": args.stop_iters,
"timesteps_total": args.stop_timesteps,
"episode_reward_mean": args.stop_reward,
}
config = {
"env": SimpleContextualBandit,
}
results = tune.run(args.run, config=config, stop=stop)
if args.as_test:
check_learning_achieved(results, args.stop_reward)