├── .gitignore
├── space_bandits
├── bayesian_nn.py
├── __init__.py
├── bandit_algorithm.py
├── neural_bandit_model.py
├── toy_problem.py
├── contextual_dataset.py
├── linear.py
└── neural_linear.py
├── setup.py
├── README.md
├── test.py
├── demo.ipynb
├── classifier_validation.ipynb
├── validation.ipynb
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | god_damnit_bayes.ipynb
2 | testing_script.ipynb
3 | space_bandits/data/
4 | __pycache__/
5 | space_bandits/__pycache__/
6 | space_bandits/core/__pyache__
7 | space_bandits/algorithms/__pycache__
8 | .ipynb_checkpoints/
9 | space_bandits.egg-info/
10 | MANIFEST
11 | dist
12 | graph_neural_model-bnn/
13 | build/
14 |
15 |
--------------------------------------------------------------------------------
/space_bandits/bayesian_nn.py:
--------------------------------------------------------------------------------
1 | """Define the abstract class for Bayesian Neural Networks."""
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | from torch import nn
8 |
9 |
10 | class BayesianNN(nn.Module):
11 | """A Bayesian neural network keeps a distribution over neural nets."""
12 |
13 | def __init__(self):
14 | pass
15 |
16 | def build_model(self):
17 | pass
18 |
19 | def train(self, data):
20 | pass
21 |
22 | def sample(self, steps):
23 | pass
24 |
--------------------------------------------------------------------------------
/space_bandits/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import numpy as np
6 | from scipy.stats import invgamma
7 | import torch
8 |
9 | from .bandit_algorithm import BanditAlgorithm
10 | from .contextual_dataset import ContextualDataset
11 | from .neural_bandit_model import NeuralBanditModel
12 | from .linear import LinearBandits
13 | from .neural_linear import NeuralBandits
14 |
15 | import os
16 | import pickle
17 | import shutil
18 |
19 | __version__ = '0.0.990'
20 |
21 | def load_model(path):
22 | """loads model from path argument"""
23 | with open(path, 'rb') as f:
24 | model = pickle.load(f)
25 | return model
26 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 | import os
3 |
4 | long_desc = """
5 | A practical library for building contextual bandits models with deep Bayesian approximation.
6 | Supports both online learning and offline training of models as well as novel methods for cross-validating CB models on historic data.
7 | """
8 |
9 | reqs= [
10 | 'torch',
11 | 'numpy',
12 | 'scipy',
13 | 'pandas',
14 | 'cython',
15 | 'scikit-learn'
16 | ]
17 | version = '0.0.993'
18 |
19 | setup(
20 | name='space-bandits',
21 | version=f'{version}',
22 | description='Deep Bayesian Contextual Bandits Library',
23 | long_description=long_desc,
24 | author='Michael Klear',
25 | author_email='michael@fellowship.ai',
26 | url='https://github.com/fellowship/space-bandits',
27 | download_url=f'https://github.com/fellowship/space-bandits/archive/v{version}.tar.gz',
28 | install_requires=reqs,
29 | packages=['space_bandits']
30 | )
31 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SpaceBandits: Deep Contextual Bandits Models made Simple
2 |
3 | Approximate Bayesian inference with neural networks has demonstrated robust performance in numerous empirical studies of contextual bandits problems [[Google Brain, 2018](https://arxiv.org/pdf/1802.09127.pdf)][[Hubspot, 2018](https://arxiv.org/pdf/1807.09809.pdf)]. Isn't it time for a package that makes deep Bayesian contextual bandits models simple to use?
4 |
5 | SpaceBandits takes the models developed and experimented on in the 2018 Google Brain research paper [Deep Bayesian Bandits Showdown: An Empirical Comparison of Bayesian Deep Networks for Thompson Sampling](https://arxiv.org/pdf/1802.09127.pdf) and makes them easy to build, train, manage, and deploy.
6 |
7 | ## Usage
8 |
9 | The alpha release of SpaceBandits, v0.0.990, is the current version. To install the latest release, use pip:
10 |
11 | `
12 | pip install space-bandits
13 | `
14 |
15 | For a introduction to using the library and the online-learning API, check out the [demo notebook](demo.ipynb).
16 | A toy problem and offline-learning API walkthrough is available in the [toy problem notebook](toy_problem.ipynb)
17 |
18 | ## Development
19 |
20 | SpaceBandits is currently in development. Please use it and report any issues you have so I can try to address them before the v0.1.0 release.
21 |
22 | Contributors are welcomed! New models from the [Google Brain paper](https://arxiv.org/pdf/1802.09127.pdf) or others might find a home here as well.
23 |
--------------------------------------------------------------------------------
/space_bandits/bandit_algorithm.py:
--------------------------------------------------------------------------------
1 | """Define the abstract class for contextual bandit algorithms."""
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | import numpy as np
8 | from sklearn.metrics import mean_squared_error
9 |
10 | def from_pandas(inp):
11 | try:
12 | inp = inp.values
13 | except:
14 | pass
15 | return inp
16 |
17 | class BanditAlgorithm(object):
18 | """A bandit algorithm must be able to do two basic operations.
19 |
20 | 1. Choose an action given a context.
21 | 2. Update its internal model given a triple (context, played action, reward).
22 | """
23 |
24 | def action(self, context):
25 | pass
26 |
27 | def update(self, context, action, reward):
28 | pass
29 |
30 | def predict_proba(self, context):
31 | """
32 |
33 | Assumes rewards are associted with a binary outcome
34 | where r <= 0 is a zero (negative) outcome,
35 | r > 0 is a one (positive) outcome.
36 |
37 | With this assumption, this function returns the probability
38 | for a positive outcome for each available action.
39 |
40 | """
41 | #deal with pandas objects
42 | context = from_pandas(context)
43 |
44 | expected_values = self.expected_values(context)
45 | reward_history = self.data_h.rewards
46 | action_history = np.array(self.data_h.actions)
47 | for a in range(self.hparams.num_actions):
48 | action_args = np.argwhere(action_history==a)
49 | slc = reward_history[action_args,a][:,0]
50 | convert = np.where(slc > 0, 1, 0)
51 | pos = convert.sum()
52 | pos_weight = pos/len(slc)
53 | center = np.quantile(expected_values[a], (1-pos_weight))
54 | expected_values[a] = (expected_values[a] - center)/expected_values[a].std()
55 |
56 | def sigmoid(x):
57 | return 1 / (1 + np.exp(-x))
58 |
59 | probas = sigmoid(expected_values)
60 | return probas
61 |
62 | def get_sscore(self, context, action, reward):
63 | """
64 |
65 | Computes the contextual bandits score S
66 | on some provided validation data
67 | (context, action, reward triplet).
68 |
69 | Returns a singular score value S.
70 | 0 < S < 1 indicates some convergence (higher is better)
71 | S < 0 indicates you're better off with a multi-arm bandit model.
72 |
73 | """
74 | #deal with pandas objects
75 | context = from_pandas(context)
76 | action = from_pandas(action)
77 | reward = from_pandas(reward)
78 |
79 | #recall training data
80 | past_actions = np.array(self.data_h.actions)
81 | past_rewards = np.array(self.data_h.rewards)
82 |
83 | #compute naive expected rewards
84 | E_b = []
85 | for a in range(self.hparams['num_actions']):
86 | inds = np.argwhere(past_actions==a)
87 | slc = past_rewards[inds, a][:, 0]
88 | E = slc.mean()
89 | E_b.append(E)
90 | Err_b = []
91 |
92 | #compute benchmark error
93 | for a in range(self.hparams['num_actions']):
94 | args = np.argwhere(action==a)[:, 0]
95 | slc = reward[args]
96 | y_pred = [E_b[a] for x in range(len(slc))]
97 | y_true = slc
98 | error = mean_squared_error(y_pred, y_true)
99 | Err_b.append(error)
100 | Err_b = np.array(Err_b)
101 |
102 | #compute validation error
103 | bal = []
104 | expected_values = self.expected_values(context)
105 | Err_m = []
106 | for a in range(self.hparams['num_actions']):
107 | args = np.argwhere(action==a)[:, 0]
108 | #record representation of action a
109 | bal.append(len(args))
110 | y_pred = expected_values[a, args]
111 | y_true = reward[args]
112 | E = mean_squared_error(y_pred, y_true)
113 | Err_m.append(E)
114 | bal = np.array(bal) / sum(bal)
115 | rat_vec = 1 - Err_m/Err_b
116 | avg = np.average(rat_vec, weights=bal)
117 |
118 | return avg
119 |
--------------------------------------------------------------------------------
/space_bandits/neural_bandit_model.py:
--------------------------------------------------------------------------------
1 | """Define a family of neural network architectures for bandits.
2 | The network accepts different type of optimizers that could lead to different
3 | approximations of the posterior distribution or simply to point estimates.
4 | """
5 |
6 | from __future__ import absolute_import
7 | from __future__ import division
8 | from __future__ import print_function
9 |
10 | import torch
11 | from torch import nn
12 | import torch.nn.functional as F
13 |
14 | from .bayesian_nn import BayesianNN
15 |
16 | def build_action_mask(actions, num_actions):
17 | """
18 | Takes a torch tensor with integer values.
19 | Returns a one-hot encoded version, where
20 | each column corresponds to a single action.
21 | """
22 | ohe = torch.zeros((len(actions), num_actions))
23 | actions = actions.reshape(-1, 1)
24 | return ohe.scatter_(1, actions, 1)
25 |
26 | def build_target(rewards, actions, num_actions):
27 | """
28 | Takes a torch tensor with floating point values.
29 | Returns a one-hot encoded version, where
30 | each column corresponds to a single action.
31 | The value is the observed reward.
32 | """
33 | ohe = torch.zeros((len(actions), num_actions))
34 | actions = actions.reshape(-1, 1)
35 | return ohe.scatter_(1, actions, rewards)
36 |
37 |
38 | class NeuralBanditModel(nn.Module):
39 | """Implements a neural network for bandit problems."""
40 |
41 | def __init__(self, optimizer, hparams, name):
42 | """Saves hyper-params and builds a torch NN."""
43 | super(NeuralBanditModel, self).__init__()
44 | self.opt_name = optimizer
45 | self.name = name
46 | self.hparams = hparams
47 | self.verbose = self.hparams["verbose"]
48 | self.times_trained = 0
49 | self.lr = self.hparams["initial_lr"]
50 | if self.hparams['activation'] == 'relu':
51 | self.activation = F.relu
52 | else:
53 | act = self.hparams['activation']
54 | msg = f'activation {act} not implimented'
55 | raise Exception(msg)
56 | self.layers = []
57 | self.build_model()
58 | self.optim = self.select_optimizer()
59 | self.loss = nn.modules.loss.MSELoss()
60 |
61 | def build_layer(self, inp_dim, out_dim):
62 | """Builds a layer with input x; dropout and layer norm if specified."""
63 |
64 | init_s = self.hparams.get('init_scale', 0.3)
65 | #these features not currently implemented
66 | layer_n = self.hparams.get("layer_norm", False)
67 | dropout = self.hparams.get("use_dropout", False)
68 |
69 | layer = nn.modules.linear.Linear(
70 | inp_dim,
71 | out_dim
72 | )
73 | nn.init.uniform_(layer.weight, a=-init_s, b=init_s)
74 | name = f'layer {len(self.layers)}'
75 | self.add_module(name, layer)
76 | return layer
77 |
78 | def forward(self, x):
79 | """forward pass of the neural network"""
80 | for i, layer in enumerate(self.layers):
81 | x = layer(x)
82 | if i != len(self.layers)-1:
83 | x = self.activation(x)
84 | return x
85 |
86 | def build_model(self):
87 | """
88 | Defines the actual NN model with fully connected layers.
89 | """
90 | for i, layer in enumerate(self.hparams['layer_sizes']):
91 | if i==0:
92 | inp_dim = self.hparams['context_dim']
93 | else:
94 | inp_dim = self.hparams['layer_sizes'][i-1]
95 | out_dim = self.hparams['layer_sizes'][i]
96 | new_layer = self.build_layer(inp_dim, out_dim)
97 | self.layers.append(new_layer)
98 | output_layer = nn.modules.linear.Linear(out_dim, self.hparams['num_actions'])
99 | self.layers.append(output_layer)
100 |
101 | def assign_lr(self, lr=None):
102 | """
103 | Resets the learning rate to input argument value "lr".
104 | """
105 | if lr is None:
106 | lr = self.lr
107 | for param_group in self.optim.param_groups:
108 | param_group['lr'] = lr
109 |
110 | def select_optimizer(self):
111 | """Selects optimizer. To be extended (SGLD, KFAC, etc)."""
112 | lr = self.hparams['initial_lr']
113 | return torch.optim.RMSprop(self.parameters(), lr=lr)
114 |
115 | def scale_weights(self):
116 | init_s = self.hparams.get('init_scale', 0.3)
117 | for layer in self.layers:
118 | nn.init.uniform_(layer.weight, a=-init_s, b=init_s)
119 |
120 | def do_step(self, x, y, w, step):
121 |
122 | decay_rate = self.hparams.get('lr_decay_rate', 0.5)
123 | base_lr = self.hparams.get('initial_lr', 0.1)
124 |
125 | lr = base_lr * (1 / (1 + (decay_rate * step)))
126 | self.assign_lr(lr)
127 |
128 | y_hat = self.forward(x.float())
129 | y_hat *= w
130 | ls = self.loss(y_hat, y.float())
131 | ls.backward()
132 | clip = self.hparams['max_grad_norm']
133 | torch.nn.utils.clip_grad_norm_(self.parameters(), clip)
134 |
135 | self.optim.step()
136 | self.optim.zero_grad()
137 |
138 | def train(self, data, num_steps):
139 | """Trains the network for num_steps, using the provided data.
140 | Args:
141 | data: ContextualDataset object that provides the data.
142 | num_steps: Number of minibatches to train the network for.
143 | """
144 |
145 | if self.verbose:
146 | print("Training {} for {} steps...".format(self.name, num_steps))
147 |
148 | batch_size = self.hparams.get('batch_size', 512)
149 |
150 | data.scale_contexts()
151 | for step in range(num_steps):
152 | x, y, w = data.get_batch_with_weights(batch_size, scaled=True)
153 | self.do_step(x, y, w, step)
154 |
155 | def get_representation(self, contexts):
156 | """
157 | Given input contexts, returns representation
158 | "z" vector.
159 | """
160 | x = contexts
161 | with torch.no_grad():
162 | for i, layer in enumerate(self.layers[:-1]):
163 | x = layer(x)
164 | x = self.activation(x)
165 | return x
166 |
--------------------------------------------------------------------------------
/space_bandits/toy_problem.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | from random import random, randint
4 |
5 | def get_customer(ctype=None):
6 | """Customers come from two feature distributions.
7 | Class 1: mean age 25, var 5 years, min age 18
8 | mean ARPU 100, var 15
9 | Class 2: mean age 45, var 6 years
10 | mean ARPU 50, var 25
11 | """
12 | if ctype is None:
13 | if random() > .5: #coin toss
14 | ctype = 1
15 | else:
16 | ctype = 2
17 | age = 0
18 | ft = -1
19 | if ctype == 1:
20 | while age < 18:
21 | age = np.random.normal(25, 5)
22 | while ft < 0:
23 | ft = np.random.normal(100, 15)
24 | if ctype == 2:
25 | while age < 18:
26 | age = np.random.normal(45, 6)
27 | while ft < 0:
28 | ft = np.random.normal(50, 25)
29 | age = round(age)
30 | return ctype, (age, ft)
31 |
32 | def get_rewards(customer):
33 | """
34 | There are three actions:
35 | promo 1: low value. 10 dollar if accept
36 | promo 2: mid value. 25 dollar if accept
37 | promo 3: high value. 100 dollar if accept
38 |
39 | Both groups are unlikely to accept promo 2.
40 | Group 1 is more likely to accept promo 1.
41 | Group 2 is slightly more likely to accept promo 3.
42 |
43 | The optimal choice for group 1 is promo 1; 90% acceptance for
44 | an expected reward of 9 dollars each.
45 | Group 2 accepts with 25% rate for expected 2.5 dollar reward
46 |
47 | The optimal choice for group 2 is promo 3; 20% acceptance for an expected
48 | reward of 20 dollars each.
49 | Group 1 accepts with 2% for expected reward of 2 dollars.
50 |
51 | The least optimal choice in all cases is promo 2; 10% acceptance rate for both groups
52 | for an expected reward of 2.5 dollars.
53 | """
54 | if customer[0] == 1: #group 1 customer
55 | if random() > .1:
56 | reward1 = 10
57 | else:
58 | reward1 = 0
59 | if random() > .90:
60 | reward2 = 25
61 | else:
62 | reward2 = 0
63 | if random() > .98:
64 | reward3 = 100
65 | else:
66 | reward3 = 0
67 | if customer[0] == 2: #group 2 customer
68 | if random() > .75:
69 | reward1 = 10
70 | else:
71 | reward1 = 0
72 | if random() > .90:
73 | reward2 = 25
74 | else:
75 | reward2 = 0
76 | if random() > .80:
77 | reward3 = 100
78 | else:
79 | reward3 = 0
80 | return np.array([reward1, reward2, reward3])
81 |
82 | def get_cust_reward():
83 | """returns a customer and reward vector"""
84 | cust = get_customer()
85 | reward = get_rewards(cust)
86 | fts = cust[1]
87 | return np.array([fts])/100, reward
88 |
89 | def generate_dataframe(n_rows):
90 | df = pd.DataFrame()
91 | ages = []
92 | ARPUs = []
93 | actions = []
94 | rewards = []
95 | for i in range(n_rows):
96 | cust = get_customer()
97 | reward_vec = get_rewards(cust)
98 | context = np.array([cust[1]])
99 | ages.append(context[0, 0])
100 | ARPUs.append(context[0, 1])
101 | action = np.random.randint(0,3)
102 | actions.append(action)
103 | reward = reward_vec[action]
104 | rewards.append(reward)
105 |
106 | df['age'] = ages
107 | df['ARPU'] = ARPUs
108 | df['action'] = actions
109 | df['reward'] = rewards
110 |
111 | return df
112 |
113 | def get_customer_nl(ctype=None):
114 | """Customers come from two feature distributions.
115 | Class 1: mean age 25, var 5 years, min age 18
116 | mean ARPU 100, var 15
117 | Class 2: mean age 45, var 6 years
118 | mean ARPU 50, var 25
119 | """
120 | if ctype is None:
121 | ctype = randint(0,2)
122 | age = 0
123 | ft = -1
124 | if ctype == 0:
125 | while age < 18:
126 | age = np.random.normal(25, 5)
127 | ft = 125 - .1*(age-25)*(age-25) + np.random.normal(0, 4)
128 | if ctype == 1:
129 | while age < 18:
130 | age = np.random.normal(35, 2)
131 | while ft < 0:
132 | ft = np.random.normal(75, 3)
133 | if ctype == 2:
134 | while age < 18:
135 | age = np.random.normal(45, 6)
136 | ft = 25 + .25*(age-45)*(age-45) + np.random.normal(0, 4)
137 | age = round(age)
138 | return ctype, (age, ft)
139 |
140 | def get_rewards_nl(customer):
141 | """
142 | There are three actions:
143 | promo 1: low value. 10 dollar if accept
144 | promo 2: mid value. 25 dollar if accept
145 | promo 3: high value. 100 dollar if accept
146 |
147 | Expected Value Matrix:
148 |
149 | group1|group2|group3
150 | ----------------------------
151 | promo1| $9 | $1 | $1
152 | ----------------------------
153 | promo2| $2.5 | $12.5| $1.25
154 | ----------------------------
155 | promo3| $1 | $5 | $25
156 |
157 | We can see each group has an optimal choice.
158 | """
159 | if customer[0] == 0: #group 1 customer
160 | if random() > .1:
161 | reward1 = 10
162 | else:
163 | reward1 = 0
164 | if random() > .90:
165 | reward2 = 25
166 | else:
167 | reward2 = 0
168 | if random() > .99:
169 | reward3 = 100
170 | else:
171 | reward3 = 0
172 | if customer[0] == 1: #group 2 customer
173 | if random() > .9:
174 | reward1 = 10
175 | else:
176 | reward1 = 0
177 | if random() > .50:
178 | reward2 = 25
179 | else:
180 | reward2 = 0
181 | if random() > .95:
182 | reward3 = 100
183 | else:
184 | reward3 = 0
185 | if customer[0] == 2: #group 3 customer
186 | if random() > .9:
187 | reward1 = 10
188 | else:
189 | reward1 = 0
190 | if random() > .95:
191 | reward2 = 25
192 | else:
193 | reward2 = 0
194 | if random() > .75:
195 | reward3 = 100
196 | else:
197 | reward3 = 0
198 | return np.array([reward1, reward2, reward3])
199 |
200 | def get_cust_reward_nl():
201 | """
202 | returns a customer and reward vector
203 | for nonlinear problem
204 | """
205 | cust = get_customer()
206 | reward = get_rewards(cust)
207 | age = cust[1]
208 | return np.array([age]), reward
209 |
210 | def generate_biased_dataframe(n_rows):
211 | df = pd.DataFrame()
212 | ages = []
213 | ARPUs = []
214 | actions = []
215 | rewards = []
216 | for i in range(n_rows):
217 | cust = get_customer()
218 | reward_vec = get_rewards(cust)
219 | context = np.array([cust[1]])
220 | age = context[0, 0]
221 | ARPU = context[0, 1]
222 | ages.append(age)
223 | ARPUs.append(ARPU)
224 | if ARPU <= 50:
225 | action = 0
226 | elif ARPU <= 100:
227 | action = 1
228 | else:
229 | action = 2
230 | actions.append(action)
231 | reward = reward_vec[action]
232 | rewards.append(reward)
233 |
234 | df['age'] = ages
235 | df['ARPU'] = ARPUs
236 | df['action'] = actions
237 | df['reward'] = rewards
238 |
239 | return df
240 |
--------------------------------------------------------------------------------
/space_bandits/contextual_dataset.py:
--------------------------------------------------------------------------------
1 | """Define a data buffer for contextual bandit algorithms."""
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 |
8 | import numpy as np
9 | import torch
10 | import pandas as pd
11 | from scipy.sparse import coo_matrix
12 |
13 | import warnings
14 | warnings.filterwarnings("ignore", category=DeprecationWarning)
15 |
16 | class ContextualDataset(object):
17 | """The buffer is able to append new data, and sample random minibatches."""
18 |
19 | def __init__(self, context_dim, num_actions, memory_size=-1, intercept=False):
20 | """Creates a ContextualDataset object.
21 | The data is stored in attributes: contexts and rewards.
22 | The sequence of taken actions are stored in attribute actions.
23 | Args:
24 | context_dim: Dimension of the contexts.
25 | num_actions: Number of arms for the multi-armed bandit.
26 | memory_size: Specify the number of examples to store in memory.
27 | if memory_size = -1, all data will be stored.
28 | intercept: If True, it adds a constant (1.0) dimension to each context X,
29 | at the end.
30 | """
31 |
32 | self._context_dim = context_dim
33 | self._num_actions = num_actions
34 | self.contexts = None
35 | self.scaled_contexts = None
36 | self.rewards = None
37 | self.actions = []
38 | self.memory_size = memory_size
39 | self.intercept = intercept
40 | self.scaling_data = []
41 |
42 | def add(self, context, action, reward):
43 | """Adds a new triplet (context, action, reward) to the dataset.
44 | The reward for the actions that weren't played is assumed to be zero.
45 | Args:
46 | context: A d-dimensional vector with the context.
47 | action: Integer between 0 and k-1 representing the chosen arm.
48 | reward: Real number representing the reward for the (context, action).
49 | """
50 | if not isinstance(context, torch.Tensor):
51 | context = torch.tensor(context.astype(float))
52 | if len(context.shape) > 1:
53 | context = context.reshape(-1)
54 | if self.intercept:
55 | c = context[:]
56 | c = torch.cat((c, torch.tensor([1.0]).double()))
57 | c = c.reshape((1, self.context_dim + 1))
58 | else:
59 | if type(context) == type(torch.tensor(0)):
60 | c = context[:].reshape((1, self.context_dim))
61 | else:
62 | c = torch.tensor(context[:]).reshape((1, self.context_dim))
63 |
64 |
65 |
66 | if self.contexts is None:
67 |
68 | self.contexts = c
69 | else:
70 | self.contexts = torch.cat((self.contexts, c))
71 |
72 |
73 |
74 | r = torch.zeros((1, self.num_actions))
75 | r[0, action] = float(reward)
76 | if self.rewards is None:
77 | self.rewards = r
78 | else:
79 | self.rewards = torch.cat((self.rewards, r))
80 |
81 |
82 | self.actions.append(action)
83 |
84 | #Drop oldest example if memory constraint
85 | if self.memory_size != -1:
86 | if self.contexts.shape[0] > self.memory_size:
87 | self.contexts = self.contexts[1:, :]
88 | self.rewards = self.rewards[1:, :]
89 | self.actions = self.actions[1:]
90 | #Assert lengths match
91 | assert len(self.actions) == len(self.rewards)
92 | assert len(self.actions) == len(self.contexts)
93 |
94 | def _replace_data(self, contexts=None, actions=None, rewards=None):
95 | if contexts is not None:
96 | self.contexts = contexts
97 | if actions is not None:
98 | self.actions = actions
99 | if rewards is not None:
100 | self.rewards = rewards
101 |
102 | def _ingest_data(self, contexts, actions, rewards):
103 | """Ingests bulk data."""
104 | if isinstance(rewards, pd.DataFrame) or isinstance(rewards, pd.Series):
105 | rewards = rewards.values
106 | if isinstance(actions, pd.DataFrame) or isinstance(actions, pd.Series):
107 | actions = actions.values
108 | if isinstance(contexts, pd.DataFrame) or isinstance(contexts, pd.Series):
109 | contexts = contexts.values
110 | if not isinstance(rewards, torch.Tensor):
111 | rewards = torch.tensor(rewards)
112 | if not isinstance(actions, torch.Tensor):
113 | actions = torch.tensor(actions)
114 | if not isinstance(contexts, torch.Tensor):
115 | contexts = torch.tensor(contexts)
116 | data_length = len(rewards)
117 | if self.memory_size != -1:
118 | if data_length + len(self.rewards) > self.memory_size:
119 | print('Cannot add more examples: ')
120 | raise Exception('Too many examples for specified memory_size.')
121 | try:
122 | contexts = contexts.reshape(-1, self.context_dim)
123 | except:
124 | print('Got bad data contexts shape: ', contexts.shape)
125 | raise Exception('Expected: ({}, {})'.format(data_length, self.context_dim))
126 | if self.intercept:
127 | #add intercepts
128 | contexts = torch.cat([contexts, torch.ones((data_length, 1)).double()], dim=1)
129 | try:
130 | assert len(contexts) == data_length
131 | assert len(actions) == data_length
132 | except AssertionError:
133 | raise AssertionError('Data lengths inconsistent.')
134 | if self.contexts is None:
135 | self.contexts = contexts
136 | else:
137 | self.contexts = torch.cat((self.contexts, contexts))
138 |
139 | rewards_array = coo_matrix((np.array(rewards), (np.arange(data_length), np.array(actions)))).toarray()
140 | n_missing_dims = self.num_actions - rewards_array.shape[1]
141 | if n_missing_dims != 0: #case for issue 20
142 | missing_dims = np.zeros((rewards_array.shape[0], n_missing_dims))
143 | rewards_array = np.concatenate([rewards_array, missing_dims], axis=1)
144 | rewards_array = torch.tensor(rewards_array).float()
145 | if self.rewards is None:
146 | self.rewards = rewards_array
147 | else:
148 | self.rewards = torch.cat((self.rewards, rewards_array.float()))
149 |
150 | self.actions = self.actions + list(actions)
151 |
152 | def get_batch(self, batch_size=512):
153 | """Returns a random minibatch of (contexts, rewards) with batch_size."""
154 | n, _ = self.contexts.shape
155 | ind = np.random.choice(range(n), batch_size)
156 | return self.contexts[ind, :], self.rewards[ind, :], torch.tensor(self.actions)[ind]
157 |
158 | def get_data(self, action):
159 | """Returns all (context, reward) where the action was played."""
160 | n, _ = self.contexts.shape
161 | ind = np.argwhere(np.array(self.actions) == action).reshape(-1)
162 | return self.contexts[ind, :], self.rewards[ind, action]
163 |
164 | def get_data_with_weights(self):
165 | """Returns all observations with one-hot weights for actions."""
166 | weights = torch.zeros((self.contexts.shape[0], self.num_actions))
167 | a_ind = np.array([(i, val) for i, val in enumerate(self.actions)])
168 | weights[a_ind[:, 0], a_ind[:, 1]] = 1.0
169 | return self.contexts, self.rewards, weights
170 |
171 | def get_batch_with_weights(self, batch_size, scaled=False):
172 | """Returns a random mini-batch with one-hot weights for actions."""
173 |
174 | n, _ = self.contexts.shape
175 | if self.memory_size == -1:
176 | # use all the data
177 | ind = np.random.choice(range(n), batch_size)
178 | else:
179 | # use only buffer (last buffer_s obs)
180 | ind = np.random.choice(range(max(0, n - self.memory_size), n), batch_size)
181 |
182 | weights = torch.zeros((batch_size, self.num_actions))
183 | sampled_actions = torch.tensor(self.actions)[ind]
184 | a_ind = torch.tensor([(i, val) for i, val in enumerate(sampled_actions)])
185 | weights[a_ind[:, 0], a_ind[:, 1]] = 1.0
186 | if scaled:
187 | ctx = self.scaled_contexts[ind, :]
188 | else:
189 | ctx = self.contexts[ind, :]
190 | return ctx, self.rewards[ind, :], weights
191 |
192 | def num_points(self, f=None):
193 | """Returns number of points in the buffer (after applying function f)."""
194 | if f is not None:
195 | return f(self.contexts.shape[0])
196 | return self.contexts.shape[0]
197 |
198 | def scale_contexts(self, contexts=None):
199 | """
200 | Performs mean/std scaling operation on contexts.
201 | if contexts is provided as argument, returns scaled version
202 | (scaled by statistics of data in dataset.)
203 | """
204 | means = self.contexts.mean(dim=0)
205 | stds = self.contexts.std(dim=0)
206 | stds[stds==0] = 1
207 | self.scaled_contexts = self.contexts.clone()
208 | for col in range(self._context_dim):
209 | self.scaled_contexts[:, col] -= means[col]
210 | self.scaled_contexts[:, col] /= stds[col]
211 | if contexts is not None:
212 | if not isinstance(contexts, torch.Tensor):
213 | contexts = torch.tensor(contexts)
214 | result = contexts
215 | for col in range(self._context_dim):
216 | result[:, col] -= means[col]
217 | result[:, col] /= stds[col]
218 | return result
219 |
220 | def get_contexts(self, scaled=False):
221 | if scaled:
222 | return self.scaled_contexts
223 | else:
224 | return self.contexts
225 |
226 | def __len__(self):
227 | return len(self.actions)
228 |
229 | @property
230 | def context_dim(self):
231 | return self._context_dim
232 |
233 | @property
234 | def num_actions(self):
235 | return self._num_actions
236 |
237 | @property
238 | def contexts(self):
239 | return self._contexts
240 |
241 | @contexts.setter
242 | def contexts(self, value):
243 | self._contexts = value
244 |
245 | @property
246 | def actions(self):
247 | return self._actions
248 |
249 | @actions.setter
250 | def actions(self, value):
251 | self._actions = value
252 |
253 | @property
254 | def rewards(self):
255 | return self._rewards
256 |
257 | @rewards.setter
258 | def rewards(self, value):
259 | self._rewards = value
260 |
--------------------------------------------------------------------------------
/space_bandits/linear.py:
--------------------------------------------------------------------------------
1 | """Contextual algorithm that keeps a full linear posterior for each arm."""
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | import numpy as np
8 |
9 | np.seterr(all='warn')
10 |
11 | from scipy.stats import invgamma
12 |
13 | from .bandit_algorithm import BanditAlgorithm
14 | from .contextual_dataset import ContextualDataset
15 | import torch
16 |
17 | import pickle
18 | import multiprocessing
19 |
20 | import warnings
21 | warnings.filterwarnings("ignore", category=DeprecationWarning)
22 |
23 | #These functions help with multiprocessing random number generation.
24 | mus = None
25 | covs = None
26 |
27 | def get_mn(i):
28 | """helper function to parallelize random number generation"""
29 | mu = mus[i]
30 | cov = covs[i]
31 | min_eig = np.min(np.real(np.linalg.eigvals(cov)))
32 | if min_eig < 0:
33 | cov -= 10*min_eig * np.eye(*cov.shape)
34 | return np.random.multivariate_normal(mu, cov)
35 |
36 | def parallelize_multivar(mus, covs, n_threads=-1):
37 | """parallelizes mn computation"""
38 | if n_threads == -1:
39 | try:
40 | cpus = multiprocessing.cpu_count()-1
41 | except NotImplementedError:
42 | cpus = 2 # arbitrary default
43 | else:
44 | cpus = n_threads
45 |
46 | with multiprocessing.Pool(processes=cpus) as pool:
47 | samples = pool.map(get_mn, range(len(mus)))
48 | return samples
49 |
50 |
51 | class LinearBandits(BanditAlgorithm):
52 | """Thompson Sampling with independent linear models and unknown noise var."""
53 |
54 | def __init__(
55 | self,
56 | num_actions,
57 | num_features,
58 | name='linear_model',
59 | a0=6,
60 | b0=6,
61 | lambda_prior=0.25,
62 | initial_pulls=2
63 | ):
64 | """
65 | A bayesian-linear contextual bandits model.
66 | Assume a linear model for each action i: reward = context^T beta_i + noise
67 | Each beta_i has a Gaussian prior (lambda parameter), each sigma2_i (noise
68 | level) has an inverse Gamma prior (a0, b0 parameters). Mean, covariance,
69 | and precision matrices are initialized, and the ContextualDataset created.
70 |
71 | num_actions (int): the number of available actions in problem
72 |
73 | num_features (int): the length of context vector, a.k.a. the number of features
74 |
75 | a0 (int): initial alpha value (default 6)
76 |
77 | b0 (int): initial beta_0 value (default 6)
78 |
79 | lambda_prior (float): lambda prior parameter(default 0.25)
80 |
81 | initial_pulls (int): number of pure exploration rounds before Thompson sampling
82 | """
83 | hparams = {
84 | 'num_actions':num_actions,
85 | 'context_dim':num_features,
86 | 'a0':a0,
87 | 'b0':b0,
88 | 'lambda_prior':lambda_prior,
89 | 'initial_pulls':initial_pulls
90 | }
91 |
92 | self.name = name
93 | self.hparams = hparams
94 |
95 | # Gaussian prior for each beta_i
96 | self._lambda_prior = self.hparams['lambda_prior']
97 |
98 | self.mu = [
99 | np.zeros(self.hparams['context_dim'] + 1)
100 | for _ in range(self.hparams['num_actions'])
101 | ]
102 |
103 | self.cov = [(1.0 / self.lambda_prior) * np.eye(self.hparams['context_dim'] + 1)
104 | for _ in range(self.hparams['num_actions'])]
105 |
106 | self.precision = [
107 | self.lambda_prior * np.eye(self.hparams['context_dim'] + 1)
108 | for _ in range(self.hparams['num_actions'])
109 | ]
110 |
111 | # Inverse Gamma prior for each sigma2_i
112 | self._a0 = self.hparams['a0']
113 | self._b0 = self.hparams['b0']
114 |
115 | self.a = [self._a0 for _ in range(self.hparams['num_actions'])]
116 | self.b = [self._b0 for _ in range(self.hparams['num_actions'])]
117 |
118 | self.t = 0
119 | self.data_h = ContextualDataset(self.hparams['context_dim'],
120 | self.hparams['num_actions'],
121 | intercept=True)
122 |
123 | def expected_values(self, context):
124 | """
125 | Computes expected values from context. Does not consider uncertainty.
126 | Args:
127 | context: Context for which the action need to be chosen.
128 | Returns:
129 | expected reward vector.
130 | """
131 | # Compute sampled expected values, intercept is last component of beta
132 | vals = [
133 | np.dot(self.mu[i][:-1], context.T) + self.mu[i][-1]
134 | for i in range(self.hparams['num_actions'])
135 | ]
136 | return np.array(vals)
137 |
138 | def _sample(self, context, parallelize=False, n_threads=-1):
139 | """
140 | Samples beta's from posterior, and samples from expected values.
141 | Args:
142 | context: Context for which the action need to be chosen.
143 | Returns:
144 | action: sampled reward vector."""
145 |
146 | # Sample sigma2, and beta conditional on sigma2
147 | context = context.reshape(-1, self.hparams['context_dim'])
148 | n_rows = len(context)
149 | a_projected = np.repeat(np.array(self.a)[np.newaxis, :], n_rows, axis=0)
150 | sigma2_s = self.b * invgamma.rvs(a_projected)
151 | if n_rows == 1:
152 | sigma2_s = sigma2_s.reshape(1, -1)
153 | beta_s = []
154 | try:
155 | for i in range(self.hparams['num_actions']):
156 | global mus
157 | global covs
158 | mus = np.repeat(self.mu[i][np.newaxis, :], n_rows, axis=0)
159 | s2s = sigma2_s[:, i]
160 | rep = np.repeat(s2s[:, np.newaxis], self.hparams['context_dim']+1, axis=1)
161 | rep = np.repeat(rep[:, :, np.newaxis], self.hparams['context_dim']+1, axis=2)
162 | covs = np.repeat(self.cov[i][np.newaxis, :, :], n_rows, axis=0)
163 | covs = rep * covs
164 | if parallelize:
165 | multivariates = parallelize_multivar(mus, covs, n_threads=n_threads)
166 | else:
167 | multivariates = [np.random.multivariate_normal(mus[j], covs[j]) for j in range(n_rows)]
168 | beta_s.append(multivariates)
169 | except np.linalg.LinAlgError as e:
170 | # Sampling could fail if covariance is not positive definite
171 | # Todo: Fix This
172 | print('Exception when sampling from {}.'.format(self.name))
173 | print('Details: {} | {}.'.format(e.message, e.args))
174 | d = self.hparams['context_dim'] + 1
175 | for i in range(self.hparams['num_actions']):
176 | multivariates = [np.random.multivariate_normal(np.zeros((d)), np.eye(d)) for j in range(n_rows)]
177 | beta_s.append(multivariates)
178 | beta_s = np.array(beta_s)
179 |
180 |
181 | # Compute sampled expected values, intercept is last component of beta
182 | vals = [
183 | (beta_s[i, :, :-1] * context).sum(axis=-1) + beta_s[i, :, -1]
184 | for i in range(self.hparams['num_actions'])
185 | ]
186 | return np.array(vals)
187 |
188 | def action(self, context):
189 | """Samples beta's from posterior, and chooses best action accordingly.
190 | Args:
191 | context: Context for which the action need to be chosen.
192 | Returns:
193 | action: Selected action for the context.
194 | """
195 |
196 | # Round robin until each action has been selected "initial_pulls" times
197 | if self.t < self.hparams['num_actions'] * self.hparams['initial_pulls']:
198 | return self.t % self.hparams['num_actions']
199 | else:
200 | vals = self._sample(context)
201 | return np.argmax(vals)
202 |
203 | def update(self, context, action, reward):
204 | """Updates action posterior using the linear Bayesian regression formula.
205 | Args:
206 | context: Last observed context.
207 | action: Last observed action.
208 | reward: Last observed reward.
209 | """
210 | self.t += 1
211 | self.data_h.add(context, action, reward)
212 |
213 | self._update_action(action)
214 |
215 | def _update_action(self, action):
216 | """Updates posterior for given action"""
217 | # Update posterior of action with formulas: \beta | x,y ~ N(mu_q, cov_q)
218 | x, y = self.data_h.get_data(action)
219 | x = np.array(x)
220 | y = np.array(y)
221 |
222 | # The algorithm could be improved with sequential update formulas (cheaper)
223 | s = np.dot(x.T, x)
224 |
225 | # Some terms are removed as we assume prior mu_0 = 0.
226 | precision_a = s + self.lambda_prior * np.eye(self.hparams['context_dim'] + 1)
227 | cov_a = np.linalg.inv(precision_a)
228 | mu_a = np.dot(cov_a, np.dot(x.T, y))
229 |
230 | # Inverse Gamma posterior update
231 | a_post = self.a0 + x.shape[0] / 2.0
232 | b_upd = 0.5 * (np.dot(y.T, y) - np.dot(mu_a.T, np.dot(precision_a, mu_a)))
233 | b_post = self.b0 + b_upd
234 |
235 | # Store new posterior distributions
236 | self.mu[action] = mu_a
237 | self.cov[action] = cov_a
238 | self.precision[action] = precision_a
239 | self.a[action] = a_post
240 | self.b[action] = b_post
241 |
242 | def fit(self, contexts, actions, rewards, num_updates=1):
243 | """Inputs bulk data for training.
244 | Args:
245 | contexts: Set of observed contexts.
246 | actions: Corresponding list of actions.
247 | rewards: Corresponding list of rewards.
248 | """
249 | data_length = len(rewards)
250 | self.data_h._ingest_data(contexts, actions, rewards)
251 | self.t += data_length
252 | #update posterior on ingested data
253 | for n in range(num_updates):
254 | for action in range(self.data_h.num_actions):
255 | self._update_action(action)
256 |
257 | def predict(self, contexts, thompson=True, parallelize=True, n_threads=-1):
258 | """Takes a list or array-like of contexts and batch predicts on them"""
259 | try:
260 | contexts = contexts.values
261 | except:
262 | pass
263 | if thompson:
264 | reward_matrix = self._sample(contexts, parallelize=parallelize, n_threads=n_threads)
265 | else:
266 | reward_matrix = self.expected_values(contexts)
267 | return np.argmax(reward_matrix, axis=0)
268 |
269 | def save(self, path):
270 | """saves model to path"""
271 | with open(path, 'wb') as f:
272 | pickle.dump(self, f)
273 |
274 | @property
275 | def a0(self):
276 | return self._a0
277 |
278 | @property
279 | def b0(self):
280 | return self._b0
281 |
282 | @property
283 | def lambda_prior(self):
284 | return self._lambda_prior
285 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import time
3 | import torch
4 | import numpy as np
5 | import pandas as pd
6 | import pickle
7 |
8 | import subprocess
9 | import os
10 | from space_bandits.contextual_dataset import ContextualDataset
11 | from space_bandits.toy_problem import get_customer, get_rewards, get_cust_reward
12 | from space_bandits.toy_problem import generate_dataframe
13 | from space_bandits.linear import LinearBandits
14 | from space_bandits.neural_linear import NeuralBandits, load_model
15 | from space_bandits.neural_bandit_model import NeuralBanditModel, build_action_mask
16 | from space_bandits.neural_bandit_model import build_target
17 |
18 | from space_bandits.bayesian_nn import BayesianNN
19 |
20 | def create_neural_bandit_model():
21 | hparams = create_hparams()
22 | return NeuralBanditModel('RMS', hparams, 'testmodel')
23 |
24 | def create_hparams():
25 | hparams = {
26 | 'num_actions':3,
27 | 'context_dim':2,
28 | 'name':'testmodel',
29 | 'init_scale':0.3,
30 | 'activation':'relu',
31 | 'verbose':True,
32 | 'optimizer':'RMS',
33 | 'layer_sizes':[50],
34 | 'batch_size':512,
35 | 'activate_decay':True,
36 | 'initial_lr':0.1,
37 | 'max_grad_norm':5.0,
38 | 'show_training':False,
39 | 'freq_summary':1000,
40 | 'buffer_s':-1,
41 | 'initial_pulls':100,
42 | 'reset_lr':True,
43 | 'lr_decay_rate':0.5,
44 | 'training_freq':1,
45 | 'training_freq_network':50,
46 | 'training_epochs':100,
47 | 'memory_size':-1,
48 | 'a0':6,
49 | 'b0':6,
50 | 'lambda_prior':0.25
51 | }
52 | return hparams
53 |
54 | def create_linear_model():
55 | model = LinearBandits(
56 | num_actions=3,
57 | num_features=2,
58 | )
59 | return model
60 |
61 | def check_expected_values(model):
62 | customer = get_customer()
63 | fts = np.array(customer[1])
64 | values = model.expected_values(fts)
65 | return values
66 |
67 | def check_sample(model):
68 | customer = get_customer()
69 | fts = np.array(customer[1])
70 | values = model._sample(fts)
71 | return values
72 |
73 | def check_action(model):
74 | customer = get_customer()
75 | fts = np.array(customer[1])
76 | action = model.action(fts)
77 | return action
78 |
79 | def update_model(model):
80 | fts, reward = get_cust_reward()
81 | action = np.random.randint(3)
82 | context = np.array(fts).reshape(-1)
83 | reward = float(reward[action])
84 | model.update(context, action, reward)
85 | return model
86 |
87 | def fit_model(model):
88 | data = generate_dataframe(220)
89 | ctx = data[['age', 'ARPU']]
90 | actions = data['action']
91 | rewards = data['reward']
92 | model.fit(ctx, actions, rewards)
93 | return model
94 |
95 | def predict_model(model):
96 | data = generate_dataframe(220)
97 | ctx = data[['age', 'ARPU']]
98 | predictions = model.predict(ctx)
99 | return predictions
100 |
101 | def check_toy_problem():
102 | customer = get_customer()
103 | ctype, (age, ft) = customer
104 | assert isinstance(ctype, int)
105 | assert isinstance(age, int)
106 | assert isinstance(ft, float)
107 | reward = get_rewards(customer)
108 | assert reward.shape == (3,)
109 | fts, reward = get_cust_reward()
110 | df = generate_dataframe(10)
111 | assert isinstance(df, pd.DataFrame)
112 | return fts, reward
113 |
114 | def create_contextual_dataset():
115 | dataset = ContextualDataset(
116 | context_dim=5,
117 | num_actions=5,
118 | memory_size=200,
119 | intercept=True
120 | )
121 | return dataset
122 |
123 | def create_toy_contexual_dataset():
124 | dataset = ContextualDataset(
125 | context_dim=2,
126 | num_actions=3,
127 | memory_size=-1,
128 | intercept=False
129 | )
130 | for i in range(2000):
131 | fts, reward = get_cust_reward()
132 | action = i % 3
133 | r = reward[action]
134 | dataset.add(fts, action, r)
135 | return dataset
136 |
137 | def check_scale_contexts(dataset):
138 | dataset.scale_contexts()
139 |
140 | def check_add_data(dataset):
141 | context = np.random.randn(1, 5)
142 | action = np.random.randint(0,5)
143 | reward = np.random.randn()
144 | dataset.add(context, action, reward)
145 | return dataset
146 |
147 | def check_replace_data(dataset):
148 | context = dataset.contexts
149 | action = dataset.actions
150 | reward = dataset.rewards
151 | dataset._replace_data(context, action, reward)
152 | return dataset
153 |
154 | def check_ingest_data(dataset):
155 | context = np.random.randn(199, 5)
156 | action = np.random.randint(0,5, (199))
157 | reward = np.random.randn(199)
158 | dataset._ingest_data(context, action, reward)
159 | return dataset
160 |
161 | def check_get_batch(dataset):
162 | batch_size = 64
163 | ctx, r, act = dataset.get_batch(batch_size)
164 | assert ctx.shape == (batch_size, 6)
165 | assert isinstance(ctx, torch.Tensor)
166 | assert r.shape == (batch_size, 5)
167 | assert isinstance(r, torch.Tensor)
168 | assert isinstance(act, torch.Tensor)
169 | assert act.shape == (batch_size,)
170 | return ctx, r, dataset
171 |
172 | def check_get_data(dataset):
173 | action = 0
174 | ctx, r = dataset.get_data(action)
175 | assert ctx.shape[1] == 6
176 | assert isinstance(ctx, torch.Tensor)
177 | assert r.shape[0] == ctx.shape[0]
178 | assert isinstance(r, torch.Tensor)
179 | return ctx, r, dataset
180 |
181 | def check_get_data_with_weights(dataset):
182 | ctx, r, weights = dataset.get_data_with_weights()
183 | assert ctx.shape == (200, 6)
184 | assert isinstance(ctx, torch.Tensor)
185 | assert r.shape == (200,5)
186 | assert isinstance(r, torch.Tensor)
187 | assert weights.shape == (200, 5)
188 | assert isinstance(weights, torch.Tensor)
189 | return ctx, r, weights
190 |
191 | def check_get_batch_with_weights(dataset):
192 | batch_size = 64
193 | ctx, r, weights = dataset.get_batch_with_weights(batch_size)
194 | assert ctx.shape == (batch_size, 6)
195 | assert isinstance(ctx, torch.Tensor)
196 | assert r.shape == (batch_size,5)
197 | assert isinstance(r, torch.Tensor)
198 | assert weights.shape == (batch_size, 5)
199 | assert isinstance(weights, torch.Tensor)
200 | return ctx, r, weights
201 |
202 | def check_torch_gpu():
203 | return torch.cuda.is_available()
204 |
205 | def check_torch_cpu():
206 | torch.tensor([10, 0])
207 | return True
208 |
209 |
210 | class AppTest(unittest.TestCase):
211 |
212 | def setUp(self):
213 | self.startTime = time.time()
214 |
215 | def tearDown(self):
216 | t = time.time() - self.startTime
217 | print("%s: %.3f seconds" % (self.id(), t))
218 |
219 | def test_action_mask(self):
220 | dataset = self.test_contextual_dataset()
221 | _, _, actions = dataset.get_batch()
222 | ohe = build_action_mask(actions, num_actions=5)
223 | assert ohe.shape == (512, 5)
224 | for i in range(512):
225 | assert ohe[i, actions[i]] == 1
226 |
227 | def test_build_target(self):
228 | dataset = self.test_contextual_dataset()
229 | _, rewards, actions = dataset.get_batch()
230 | ohe = build_target(rewards, actions, num_actions=5)
231 | assert ohe.shape == (512, 5)
232 |
233 | def test_neural_linear_model(self):
234 | model = NeuralBandits(
235 | num_actions=3,
236 | num_features=2,
237 | training_freq_network=200,
238 | layer_sizes=[50]
239 | )
240 | fts, reward = get_cust_reward()
241 | for i in range(300):
242 | action = model.action(fts)
243 | r = reward[action]
244 | model.update(fts, action, r)
245 | df = generate_dataframe(500)
246 | X = df[['age', 'ARPU']].values
247 | A = df['action'].values
248 | R = df['reward'].values
249 | model.fit(X, A, R)
250 | model.save('test_file')
251 | model = load_model('test_file')
252 | X = df[['age', 'ARPU']].sample(2).values
253 | model.predict(X, parallelize=False)
254 | os.remove('test_file')
255 |
256 | def test_bayesian_nn(self):
257 | nn = BayesianNN()
258 |
259 | def test_neural_bandit_model(self):
260 | model = create_neural_bandit_model()
261 | assert len(model.layers) == 2
262 | dataset = create_toy_contexual_dataset()
263 | model.train(dataset, 10)
264 | ctx = dataset.get_contexts(scaled=True).float()
265 | z = model.get_representation(ctx)
266 | assert z.shape == (2000, 50)
267 | assert z.min() == 0.0
268 |
269 | def test_linear_model(self):
270 | model = create_linear_model()
271 | model = update_model(model)
272 | model = fit_model(model)
273 | values = check_expected_values(model)
274 | assert values.shape == (3,)
275 | predictions = predict_model(model)
276 | values = check_sample(model)
277 | assert values.shape == (3,1)
278 | action = check_action(model)
279 | assert isinstance(action, np.int64)
280 | model.save('test_file')
281 | assert os.path.isfile('test_file')
282 | os.remove('test_file')
283 |
284 | def test_toy_problem(self):
285 | fts, reward = check_toy_problem()
286 |
287 | def test_contextual_dataset(self):
288 | dataset = create_contextual_dataset()
289 | dataset = check_add_data(dataset)
290 | dataset = check_replace_data(dataset)
291 | dataset = check_ingest_data(dataset)
292 | dataset = check_add_data(dataset)
293 | assert dataset.num_points() == 200
294 | assert len(dataset) == 200
295 | ctx, r, dataset = check_get_batch(dataset)
296 | ctx, r, dataset = check_get_data(dataset)
297 | ctx, r, weights = check_get_data_with_weights(dataset)
298 | batch = check_get_batch_with_weights(dataset)
299 | assert isinstance(dataset.contexts, torch.Tensor)
300 | assert isinstance(dataset.rewards, torch.Tensor)
301 | assert isinstance(dataset.actions, list)
302 | check_scale_contexts(dataset)
303 | return dataset
304 |
305 | def test_update(self):
306 | model = LinearBandits(
307 | 3,
308 | 4
309 | )
310 | context = np.array([76, 120, 654326, 2])
311 | action = 1
312 | reward = 14
313 | model.update(context, action, reward)
314 |
315 | df = generate_dataframe(500)
316 |
317 | contexts = df[['age', 'ARPU']]
318 | actions = df['action']
319 | rewards = df['reward']
320 |
321 | new_model = NeuralBandits(3, 2, layer_sizes=[50, 12], verbose=False)
322 | #call .fit method; num_updates will repeat training n times
323 | new_model.fit(contexts, actions, rewards)
324 |
325 | new_context = np.array([26.0, 98.456463])
326 | action = np.random.randint(0, 2)
327 | reward = np.random.random() * 10
328 | print(action)
329 | new_model.update(new_context, action, reward)
330 |
331 | def test_torch_cpu(self):
332 | assert check_torch_cpu()
333 | return
334 |
335 | def test_issue_20(self):
336 | np.random.seed(0)
337 |
338 | model = LinearBandits(initial_pulls=2, num_actions=3, num_features=1)
339 | model.fit(
340 | contexts=pd.DataFrame(np.random.normal(loc=10, size=100)),
341 | actions=#np.array([2] + [0] * 99),
342 | #np.array([0] * 100),# doesn't work
343 | np.array([1] + [0] * 99), # doesn't work
344 | # np.array([2] + [0] * 99) works
345 | rewards=np.random.normal(loc=10, size=100),
346 | )
347 |
348 | if __name__ == '__main__':
349 | unittest.main()
350 |
--------------------------------------------------------------------------------
/demo.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# SpaceBandits Contextual Bandits Demo\n",
8 | "This notebook demonstrates the basic usage of SpaceBandits. The package is currently in development. Install with:\n",
9 | "\n",
10 | "```\n",
11 | "pip install space_bandits\n",
12 | "```\n",
13 | "\n",
14 | "## Build a Linear Model\n",
15 | "The simplest model in the packages maps contexts to expected rewards with linear coefficients. Use the model constructor function; you must specify the feature length (number of features per row) and the number of actions available."
16 | ]
17 | },
18 | {
19 | "cell_type": "code",
20 | "execution_count": 1,
21 | "metadata": {},
22 | "outputs": [],
23 | "source": [
24 | "from space_bandits import LinearBandits\n",
25 | "\n",
26 | "num_actions = 5 #five actions\n",
27 | "num_features = 10 #ten features\n",
28 | "\n",
29 | "model = LinearBandits(num_actions, num_features)"
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "metadata": {},
35 | "source": [
36 | "## Train the Model with .update() Method\n",
37 | "Use past examples of context, action, rewards to train the model. A context must have the dimension specified above; each training example must include one action (indexed from zero) and one associated reward."
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": 2,
43 | "metadata": {},
44 | "outputs": [
45 | {
46 | "name": "stdout",
47 | "output_type": "stream",
48 | "text": [
49 | "example context vector: \n",
50 | " [0.0425226 0.43738244 0.07786224 0.25217616 0.91765093 0.19091702\n",
51 | " 0.92737656 0.29993496 0.45324536 0.08770382]\n",
52 | "example action chosen: \n",
53 | " 2\n",
54 | "example reward associated with: \n",
55 | " 5\n"
56 | ]
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "context = np.random.random((10))\n",
62 | "print('example context vector: \\n', context)\n",
63 | "action = 2\n",
64 | "print('example action chosen: \\n', action)\n",
65 | "reward = 5\n",
66 | "print('example reward associated with: \\n', reward)\n",
67 | "\n",
68 | "#here we update the model:\n",
69 | "model.update(context, action, reward)"
70 | ]
71 | },
72 | {
73 | "cell_type": "markdown",
74 | "metadata": {},
75 | "source": [
76 | "## Make Decisions with .action() Method\n",
77 | "\n",
78 | "After training the model, we can use the .action() method to map a given context to the action with the highest expected reward."
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 3,
84 | "metadata": {},
85 | "outputs": [
86 | {
87 | "name": "stdout",
88 | "output_type": "stream",
89 | "text": [
90 | "new example context vector: \n",
91 | " [0.0425226 0.43738244 0.07786224 0.25217616 0.91765093 0.19091702\n",
92 | " 0.92737656 0.29993496 0.45324536 0.08770382]\n",
93 | "model suggested action: \n",
94 | "1\n"
95 | ]
96 | }
97 | ],
98 | "source": [
99 | "new_context = np.random.random((10))\n",
100 | "print('new example context vector: \\n', context)\n",
101 | "\n",
102 | "print('model suggested action: ')\n",
103 | "print(model.action(new_context))"
104 | ]
105 | },
106 | {
107 | "cell_type": "markdown",
108 | "metadata": {},
109 | "source": [
110 | "## Expected Values\n",
111 | "We can directly infer the model's expected values for each action given a context using the expected_values() method. The uncertainy on expected values is not taken into consideration in this computation."
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": 4,
117 | "metadata": {},
118 | "outputs": [
119 | {
120 | "name": "stdout",
121 | "output_type": "stream",
122 | "text": [
123 | "expected values for example context: \n",
124 | "[0. 0. 4.6483243 0. 0. ]\n"
125 | ]
126 | }
127 | ],
128 | "source": [
129 | "print('expected values for example context: ')\n",
130 | "print(model.expected_values(context))"
131 | ]
132 | },
133 | {
134 | "cell_type": "markdown",
135 | "metadata": {},
136 | "source": [
137 | "## Advanced Parameters\n",
138 | "### Memory Management\n",
139 | "The model keeps a record of all previous examples; this is useful for updating, but it's impractical in ongoing production scenarios. To limit the model's memory, specify the number of previous examples to \"remember\" using the memory_size argument.\n",
140 | "\n",
141 | "```python\n",
142 | "model = init_linear_model(num_actions, context_dim, memory_size=1000000)\n",
143 | "```\n",
144 | "\n",
145 | "The above specifies that the model only keep a running record of the last 1000000 examples.\n",
146 | "\n",
147 | "### Initial Exploration\n",
148 | "Thompson sampling gives us continuous, intelligent exploration throughout the model's lifetime. However, initial exploration can be very helpful for encouraging model convergence, especially with a cold start. Use the initial_pulls argument to force the model to explore before defaulting to Thompson sampling. The model will sequentially try each action initial_pulls number of times; this results in initial_pulls * n_actions exploratory actions.\n",
149 | "\n",
150 | "```python\n",
151 | "model = init_linear_model(num_actions, context_dim, initial_pulls=2)\n",
152 | "```\n",
153 | "\n",
154 | "The above will result in the model suggesting each action 2 times before using Thompson sampling to suggest actions.\n",
155 | "\n",
156 | "### Saving Your Model\n",
157 | "Each SpaceBandits model has a .save() method. Use it to save models for later use."
158 | ]
159 | },
160 | {
161 | "cell_type": "code",
162 | "execution_count": 5,
163 | "metadata": {},
164 | "outputs": [],
165 | "source": [
166 | "model.save('my_saved_model') #save to file my_saved_model\n",
167 | "\n",
168 | "from space_bandits import load_model\n",
169 | "\n",
170 | "model = load_model('my_saved_model') #load from same location"
171 | ]
172 | },
173 | {
174 | "cell_type": "markdown",
175 | "metadata": {},
176 | "source": [
177 | "## Building a Neural Model\n",
178 | "\n",
179 | "Linear models are powerful but inherently limited. The Neural-Linear Bayesian Contextual Bandits model, which was named and explored in the 2018 research paper [Deep Bayesian Bandits Showdown: An Empirical Comparison of Bayesian Deep Networks for Thompson Sampling](https://arxiv.org/pdf/1802.09127.pdf), uses a neural network to give the model a powerful way to map a feature vector to a latent representational feature space. These learned features are used in a standard linear model identical to the one used above.
\n",
180 | "SpaceBandits lets us deploy the same model with the API as above. In practice, designing the model is can be somewhat complicated; the neural network adds a huge number of hyperparameters. SpaceBandits uses the default parameters used in the research paper to give users a nice starting point; modifying them is easy."
181 | ]
182 | },
183 | {
184 | "cell_type": "code",
185 | "execution_count": 6,
186 | "metadata": {},
187 | "outputs": [],
188 | "source": [
189 | "from space_bandits import NeuralBandits\n",
190 | "\n",
191 | "model = NeuralBandits(num_actions, num_features)"
192 | ]
193 | },
194 | {
195 | "cell_type": "markdown",
196 | "metadata": {},
197 | "source": [
198 | "We can update the model in the same way as before. To improve training efficiency, the neural network only trains after a pre-defined number of updates. The default neural network training frequency is every 50 updates (modify the training_freq_network argument to change this); each time this occurs, the network trains for 100 epochs at each training session by default (modify the training_epochs argument to change this)."
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": 7,
204 | "metadata": {},
205 | "outputs": [
206 | {
207 | "name": "stdout",
208 | "output_type": "stream",
209 | "text": [
210 | "Training neural_model-bnn for 100 steps...\n",
211 | "Training neural_model-bnn for 100 steps...\n"
212 | ]
213 | }
214 | ],
215 | "source": [
216 | "# here we update the model 100 times.\n",
217 | "\n",
218 | "for i in range(100):\n",
219 | " context = np.random.random((10))\n",
220 | " action = np.random.randint(0, 4)\n",
221 | " reward = np.random.random() * 10\n",
222 | " model.update(context, action, reward)"
223 | ]
224 | },
225 | {
226 | "cell_type": "markdown",
227 | "metadata": {},
228 | "source": [
229 | "As with the linear model, the neural model will record all examples by default; modify the memory_size parameter (default value -1, for inf) on the constructor function to manage memory and training time."
230 | ]
231 | },
232 | {
233 | "cell_type": "markdown",
234 | "metadata": {},
235 | "source": [
236 | "## Saving a Neural Model\n",
237 | "\n",
238 | "Neural models actually consist of two models: a neural network and a Bayesian linear regression model. To manage this for saving, SpaceBandits creates a .zip file that keeps your models together."
239 | ]
240 | },
241 | {
242 | "cell_type": "code",
243 | "execution_count": 8,
244 | "metadata": {},
245 | "outputs": [],
246 | "source": [
247 | "model.save('my_neural_model.pkl')\n",
248 | "\n",
249 | "#don't forget the .zip extension when restoring your neural model.\n",
250 | "model = load_model('my_neural_model.pkl')"
251 | ]
252 | },
253 | {
254 | "cell_type": "markdown",
255 | "metadata": {},
256 | "source": [
257 | "## Expected Values\n",
258 | "We don't like black boxes. Model interpretation is critical for solid data science. Any SpaceBandits model will return its expected reward values for a given context using the .expected_values() method:"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 9,
264 | "metadata": {},
265 | "outputs": [
266 | {
267 | "data": {
268 | "text/plain": [
269 | "array([2.01993425, 5.70811732, 2.41866919, 5.86543991, 0. ])"
270 | ]
271 | },
272 | "execution_count": 9,
273 | "metadata": {},
274 | "output_type": "execute_result"
275 | }
276 | ],
277 | "source": [
278 | "model.expected_values(context)"
279 | ]
280 | },
281 | {
282 | "cell_type": "markdown",
283 | "metadata": {},
284 | "source": [
285 | "Neural models make use of a latent representation of the input features; this feature vector is called $z$ in the Google Brain research paper. You can retrieve the model's latent feature vector using the .get_representation() method."
286 | ]
287 | },
288 | {
289 | "cell_type": "code",
290 | "execution_count": 10,
291 | "metadata": {},
292 | "outputs": [
293 | {
294 | "data": {
295 | "text/plain": [
296 | "tensor([ 2.1710, 0.0000, 0.0000, 1.8167, 0.0000, 0.0000, 0.0000, 0.0000,\n",
297 | " 0.0000, 0.0000, 13.5386, 3.6377, 0.0000, 0.0000, 8.4940, 0.0000,\n",
298 | " 2.7854, 7.9246, 0.0000, 0.0000, 8.4467, 0.0000, 0.0000, 0.0000,\n",
299 | " 9.4823, 0.0000, 7.0178, 5.1963, 2.3382, 5.0501, 0.0000, 0.0000,\n",
300 | " 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,\n",
301 | " 0.4022, 0.0000, 11.3781, 0.0000, 0.0000, 0.0000, 0.3589, 0.0000,\n",
302 | " 6.1590, 0.0000])"
303 | ]
304 | },
305 | "execution_count": 10,
306 | "metadata": {},
307 | "output_type": "execute_result"
308 | }
309 | ],
310 | "source": [
311 | "model.get_representation(context)"
312 | ]
313 | },
314 | {
315 | "cell_type": "markdown",
316 | "metadata": {},
317 | "source": [
318 | "This 50-dimensional vector encodes the useful information in a context for our linear model to use. While it may not seem particularly useful at this time, remember: SpaceBandits is from the future, and we know this stuff turns out to be important ;)
\n",
319 | "By default, the neural network has one hidden layer with 50 nodes. Use a list of integers in the layer_sizes argument to the constructor to specify number of layers and nodes."
320 | ]
321 | },
322 | {
323 | "cell_type": "markdown",
324 | "metadata": {},
325 | "source": [
326 | "## Model Evaluation\n",
327 | "Evaluating bandit models in real-life situations is not easy. The only way to really tell if your model is doing well is to put it into production and compare its results to other decision-making policies. Simulations and toy problems where action/reward relationships are known are a great place to start. Unfortunately, public contextual bandits datasets are hard to come by!
\n",
328 | "For a look at some toy problems, check out the [toy problem notebook](toy_problem.ipynb)."
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": null,
334 | "metadata": {},
335 | "outputs": [],
336 | "source": []
337 | }
338 | ],
339 | "metadata": {
340 | "kernelspec": {
341 | "display_name": "Python 3",
342 | "language": "python",
343 | "name": "python3"
344 | },
345 | "language_info": {
346 | "codemirror_mode": {
347 | "name": "ipython",
348 | "version": 3
349 | },
350 | "file_extension": ".py",
351 | "mimetype": "text/x-python",
352 | "name": "python",
353 | "nbconvert_exporter": "python",
354 | "pygments_lexer": "ipython3",
355 | "version": "3.6.8"
356 | }
357 | },
358 | "nbformat": 4,
359 | "nbformat_minor": 2
360 | }
361 |
--------------------------------------------------------------------------------
/classifier_validation.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Space Bandits Model as a Classifier\n",
8 | "\n",
9 | "RMSE validation of a contextual bandits model is covered [here](validation.ipynb).
\n",
10 | "Sometimes, we want to compare our contextual bandits model \"apples to apples\" with a binary classifier. It turns out that the sigmoid function gives us a convenient way to do this.\n",
11 | "\n",
12 | "## Toy Data\n",
13 | "Using the same toy data used in the [toy problem notebook](toy_problem.ipynb), which we know converges."
14 | ]
15 | },
16 | {
17 | "cell_type": "code",
18 | "execution_count": 1,
19 | "metadata": {},
20 | "outputs": [
21 | {
22 | "data": {
23 | "text/html": [
24 | "
\n",
25 | "\n",
38 | "
\n",
39 | " \n",
40 | " \n",
41 | " | \n",
42 | " age | \n",
43 | " ARPU | \n",
44 | " action | \n",
45 | " reward | \n",
46 | "
\n",
47 | " \n",
48 | " \n",
49 | " \n",
50 | " | 0 | \n",
51 | " 41.0 | \n",
52 | " 31.705625 | \n",
53 | " 0 | \n",
54 | " 0 | \n",
55 | "
\n",
56 | " \n",
57 | " | 1 | \n",
58 | " 27.0 | \n",
59 | " 85.884541 | \n",
60 | " 0 | \n",
61 | " 10 | \n",
62 | "
\n",
63 | " \n",
64 | " | 2 | \n",
65 | " 36.0 | \n",
66 | " 17.053245 | \n",
67 | " 1 | \n",
68 | " 0 | \n",
69 | "
\n",
70 | " \n",
71 | " | 3 | \n",
72 | " 48.0 | \n",
73 | " 59.970738 | \n",
74 | " 1 | \n",
75 | " 25 | \n",
76 | "
\n",
77 | " \n",
78 | " | 4 | \n",
79 | " 47.0 | \n",
80 | " 98.454896 | \n",
81 | " 2 | \n",
82 | " 0 | \n",
83 | "
\n",
84 | " \n",
85 | "
\n",
86 | "
"
87 | ],
88 | "text/plain": [
89 | " age ARPU action reward\n",
90 | "0 41.0 31.705625 0 0\n",
91 | "1 27.0 85.884541 0 10\n",
92 | "2 36.0 17.053245 1 0\n",
93 | "3 48.0 59.970738 1 25\n",
94 | "4 47.0 98.454896 2 0"
95 | ]
96 | },
97 | "execution_count": 1,
98 | "metadata": {},
99 | "output_type": "execute_result"
100 | }
101 | ],
102 | "source": [
103 | "import numpy as np\n",
104 | "import pandas as pd\n",
105 | "from random import random, randint\n",
106 | "import matplotlib.pyplot as plt\n",
107 | "import gc\n",
108 | "%config InlineBackend.figure_format='retina'\n",
109 | "##Generate Data\n",
110 | "\n",
111 | "from space_bandits.toy_problem import generate_dataframe\n",
112 | "\n",
113 | "df = generate_dataframe(10000)\n",
114 | "df.head()"
115 | ]
116 | },
117 | {
118 | "cell_type": "markdown",
119 | "metadata": {},
120 | "source": [
121 | "We produce a dataset with randomly selected actions and 4000 rows.\n",
122 | "## Train/Validation Split\n",
123 | "We split the data into two equally-sized groups."
124 | ]
125 | },
126 | {
127 | "cell_type": "code",
128 | "execution_count": 2,
129 | "metadata": {},
130 | "outputs": [],
131 | "source": [
132 | "train = df.sample(frac=.5).copy()\n",
133 | "val = df[~df.index.isin(train.index)].copy()\n",
134 | "num_actions = len(train.action.unique())"
135 | ]
136 | },
137 | {
138 | "cell_type": "markdown",
139 | "metadata": {},
140 | "source": [
141 | "## Validation Metric\n",
142 | "We'll use the ROC AUC score as a validation metric. We'll train a simple binary classifier, a logistic regression model, to \"compete\" with our bandits model. This model simply predicts convert/no convert."
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 3,
148 | "metadata": {},
149 | "outputs": [
150 | {
151 | "name": "stderr",
152 | "output_type": "stream",
153 | "text": [
154 | "/home/alliedtoasters/miniconda3/envs/bandits/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject\n",
155 | " return f(*args, **kwds)\n"
156 | ]
157 | }
158 | ],
159 | "source": [
160 | "from sklearn.metrics import roc_auc_score\n",
161 | "from sklearn.linear_model import LogisticRegression"
162 | ]
163 | },
164 | {
165 | "cell_type": "code",
166 | "execution_count": 4,
167 | "metadata": {},
168 | "outputs": [],
169 | "source": [
170 | "train_fts = train[['age', 'ARPU']]\n",
171 | "#give actions as features\n",
172 | "campaign_fts = pd.get_dummies(train.action)\n",
173 | "campaign_fts.index = train_fts.index\n",
174 | "X_train = pd.concat([train_fts, campaign_fts], axis=1)\n",
175 | "#Get labels: we are predicting conversion, so 1 if reward != 0\n",
176 | "train['convert'] = np.where(train.reward > 0, 1, 0)\n",
177 | "Y_train = train.convert\n",
178 | "\n",
179 | "#prepare X_val for later\n",
180 | "val_fts = val[['age', 'ARPU']]\n",
181 | "campaign_fts_val = pd.get_dummies(val.action)\n",
182 | "campaign_fts_val.index = val_fts.index\n",
183 | "X_val = pd.concat([val_fts, campaign_fts_val], axis=1)\n",
184 | "#get validation labels as well\n",
185 | "val['convert'] = np.where(val.reward > 0, 1, 0)\n",
186 | "Y_val = val.convert"
187 | ]
188 | },
189 | {
190 | "cell_type": "code",
191 | "execution_count": 5,
192 | "metadata": {},
193 | "outputs": [
194 | {
195 | "name": "stdout",
196 | "output_type": "stream",
197 | "text": [
198 | "Logistic regression auc score: 0.786\n"
199 | ]
200 | },
201 | {
202 | "name": "stderr",
203 | "output_type": "stream",
204 | "text": [
205 | "/home/alliedtoasters/miniconda3/envs/bandits/lib/python3.6/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n",
206 | " FutureWarning)\n"
207 | ]
208 | }
209 | ],
210 | "source": [
211 | "classifier = LogisticRegression()\n",
212 | "classifier.fit(X_train, Y_train)\n",
213 | "pred = classifier.predict_proba(X_val)[:, 1]\n",
214 | "\n",
215 | "classifier_auc_score = roc_auc_score(Y_val, pred)\n",
216 | "print('Logistic regression auc score: ', round(classifier_auc_score, 3))"
217 | ]
218 | },
219 | {
220 | "cell_type": "markdown",
221 | "metadata": {},
222 | "source": [
223 | "## Bandits Model\n",
224 | "We fit a bandits model on the same data."
225 | ]
226 | },
227 | {
228 | "cell_type": "code",
229 | "execution_count": 6,
230 | "metadata": {},
231 | "outputs": [],
232 | "source": [
233 | "from space_bandits import NeuralBandits\n",
234 | "\n",
235 | "model = NeuralBandits(num_actions, num_features=2, layer_sizes=[50,12])"
236 | ]
237 | },
238 | {
239 | "cell_type": "code",
240 | "execution_count": 7,
241 | "metadata": {},
242 | "outputs": [
243 | {
244 | "name": "stdout",
245 | "output_type": "stream",
246 | "text": [
247 | "Training neural_model-bnn for 100 steps...\n"
248 | ]
249 | }
250 | ],
251 | "source": [
252 | "model.fit(train[['age', 'ARPU']], train['action'], train['reward'])"
253 | ]
254 | },
255 | {
256 | "cell_type": "markdown",
257 | "metadata": {},
258 | "source": [
259 | "# Get Expected Rewards\n",
260 | "We collect expected reward values and add them to the validation dataframe."
261 | ]
262 | },
263 | {
264 | "cell_type": "code",
265 | "execution_count": 8,
266 | "metadata": {},
267 | "outputs": [
268 | {
269 | "data": {
270 | "text/html": [
271 | "\n",
272 | "\n",
285 | "
\n",
286 | " \n",
287 | " \n",
288 | " | \n",
289 | " age | \n",
290 | " ARPU | \n",
291 | " action | \n",
292 | " reward | \n",
293 | " convert | \n",
294 | " 0 | \n",
295 | " 1 | \n",
296 | " 2 | \n",
297 | "
\n",
298 | " \n",
299 | " \n",
300 | " \n",
301 | " | 0 | \n",
302 | " 41.0 | \n",
303 | " 31.705625 | \n",
304 | " 0 | \n",
305 | " 0 | \n",
306 | " 0 | \n",
307 | " 41.371531 | \n",
308 | " 63.260073 | \n",
309 | " 182.308648 | \n",
310 | "
\n",
311 | " \n",
312 | " | 1 | \n",
313 | " 27.0 | \n",
314 | " 85.884541 | \n",
315 | " 0 | \n",
316 | " 10 | \n",
317 | " 1 | \n",
318 | " 185.118165 | \n",
319 | " 115.596413 | \n",
320 | " 143.854397 | \n",
321 | "
\n",
322 | " \n",
323 | " | 3 | \n",
324 | " 48.0 | \n",
325 | " 59.970738 | \n",
326 | " 1 | \n",
327 | " 25 | \n",
328 | " 1 | \n",
329 | " 139.067486 | \n",
330 | " 93.874866 | \n",
331 | " 136.292929 | \n",
332 | "
\n",
333 | " \n",
334 | " | 4 | \n",
335 | " 47.0 | \n",
336 | " 98.454896 | \n",
337 | " 2 | \n",
338 | " 0 | \n",
339 | " 0 | \n",
340 | " 227.190699 | \n",
341 | " 137.435247 | \n",
342 | " 158.761865 | \n",
343 | "
\n",
344 | " \n",
345 | " | 5 | \n",
346 | " 51.0 | \n",
347 | " 85.203130 | \n",
348 | " 1 | \n",
349 | " 0 | \n",
350 | " 0 | \n",
351 | " 207.160420 | \n",
352 | " 123.381055 | \n",
353 | " 136.992186 | \n",
354 | "
\n",
355 | " \n",
356 | "
\n",
357 | "
"
358 | ],
359 | "text/plain": [
360 | " age ARPU action reward convert 0 1 2\n",
361 | "0 41.0 31.705625 0 0 0 41.371531 63.260073 182.308648\n",
362 | "1 27.0 85.884541 0 10 1 185.118165 115.596413 143.854397\n",
363 | "3 48.0 59.970738 1 25 1 139.067486 93.874866 136.292929\n",
364 | "4 47.0 98.454896 2 0 0 227.190699 137.435247 158.761865\n",
365 | "5 51.0 85.203130 1 0 0 207.160420 123.381055 136.992186"
366 | ]
367 | },
368 | "execution_count": 8,
369 | "metadata": {},
370 | "output_type": "execute_result"
371 | }
372 | ],
373 | "source": [
374 | "expected_values = model.expected_values(val[['age', 'ARPU']].values)\n",
375 | "pred = pd.DataFrame()\n",
376 | "for a, vals in enumerate(expected_values):\n",
377 | " pred[a] = vals\n",
378 | "#expected reward values\n",
379 | "pred.index = val.index\n",
380 | "#add them to validation df\n",
381 | "val = pd.concat([val, pred], axis=1)\n",
382 | "val.head()"
383 | ]
384 | },
385 | {
386 | "cell_type": "markdown",
387 | "metadata": {},
388 | "source": [
389 | "## Applying the Sigmoid Function\n",
390 | "The bandits model treats each campaign separately, so we should apply a sigmoid function to each reward column independently. To get sensible values, mean-center and normalize each expected reward column."
391 | ]
392 | },
393 | {
394 | "cell_type": "code",
395 | "execution_count": 9,
396 | "metadata": {},
397 | "outputs": [],
398 | "source": [
399 | "val['pred'] = .5\n",
400 | "for a in range(num_actions):\n",
401 | " #mean center and normalize expected rewards\n",
402 | " val['{}_centered'.format(a)] = (val[a] - val[a].mean())/val[a].std()"
403 | ]
404 | },
405 | {
406 | "cell_type": "code",
407 | "execution_count": 10,
408 | "metadata": {},
409 | "outputs": [],
410 | "source": [
411 | "def sigmoid(x):\n",
412 | " return 1 / (1 + np.exp(-x))\n",
413 | "\n",
414 | "#Apply sigmoid to get p_pred\n",
415 | "for a in range(num_actions):\n",
416 | " #get the rows for this action\n",
417 | " slc = val[val.action==a]\n",
418 | " #pass values through sigmoid\n",
419 | " vals = sigmoid(slc['{}_centered'.format(a)].values)\n",
420 | " #assign output to appropriate rows\n",
421 | " inds = slc.index\n",
422 | " val.loc[inds, 'pred'] = vals"
423 | ]
424 | },
425 | {
426 | "cell_type": "code",
427 | "execution_count": 11,
428 | "metadata": {},
429 | "outputs": [
430 | {
431 | "name": "stdout",
432 | "output_type": "stream",
433 | "text": [
434 | "Bandits auc score: 0.625\n"
435 | ]
436 | }
437 | ],
438 | "source": [
439 | "pred = val.pred\n",
440 | "\n",
441 | "bandits_auc_score = roc_auc_score(Y_val, pred)\n",
442 | "print('Bandits auc score: ', round(bandits_auc_score, 3))"
443 | ]
444 | },
445 | {
446 | "cell_type": "markdown",
447 | "metadata": {},
448 | "source": [
449 | "## Result\n",
450 | "We see the logistic regression model performs better by this metric. This shouldn't be a surprise! The bandits model has a much harder job! It has to perform a regression for all three campaigns - the logreg model gets all the benefits of supervision and only has a single binary output."
451 | ]
452 | },
453 | {
454 | "cell_type": "code",
455 | "execution_count": null,
456 | "metadata": {},
457 | "outputs": [],
458 | "source": []
459 | }
460 | ],
461 | "metadata": {
462 | "kernelspec": {
463 | "display_name": "Python 3",
464 | "language": "python",
465 | "name": "python3"
466 | },
467 | "language_info": {
468 | "codemirror_mode": {
469 | "name": "ipython",
470 | "version": 3
471 | },
472 | "file_extension": ".py",
473 | "mimetype": "text/x-python",
474 | "name": "python",
475 | "nbconvert_exporter": "python",
476 | "pygments_lexer": "ipython3",
477 | "version": "3.6.8"
478 | }
479 | },
480 | "nbformat": 4,
481 | "nbformat_minor": 2
482 | }
483 |
--------------------------------------------------------------------------------
/validation.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Validating a Contextual Bandits Model\n",
8 | "\n",
9 | "Validation is straightforward in supervised learning because the \"ground truth\" is completely and unambiguously known. In the reinforcement learning case (RL), validation in inherently challenging due to the very nature of the problem: only partial \"ground truths\" are observed, or queried, from some unknown reward-generating process.
\n",
10 | "The following is one approach for validating contextual bandits models.\n",
11 | "\n",
12 | "## Historic Data\n",
13 | "The models used in Space Bandits benefit from direct reward approximation; given a set of features or a context, the model estimates an expected reward for each available action. This allows the model to optimize without direct access to the decision making policy used to query the reward-generating process.
\n",
14 | "The model directly regresses expected reward for each action based on a set of features. This makes regression metrics, such as RMSE, appropriate for evaluation. Due to the stochastic nature of the reward-generating process, we should not expect regression error metrics to be small. However, we would expect an optimized model to minimize such an error metric.\n",
15 | "## Naive Benchmark\n",
16 | "In the multi-arm bandit case, the expected reward for a given action can be approximated by computing the mean of observed rewards from this action. This special case provides a convenient naive benchmark for the expected value of each action, which we call $\\mathbb{E}_{b}[\\mathcal{A}]$.
\n",
17 | "We can use $\\mathbb{E}_{b}[\\mathcal{A}]$ to compute a benchmark error vector, $\\epsilon_{b}[\\mathcal{A}]$ for each action given a validation set by simpling using $\\mathbb{E}_{b}[\\mathcal{a}]$ as a naive predicted reward for a chosen action in the validation set and computing the RMSE against the observed reward, $\\mathcal{R}_{obs}$. \n",
18 | "$$\n",
19 | "\\epsilon_{b}[\\mathcal{A}] = \\sum_{n_{a}=0}^{N_{obs, a}}RMSE(\\mathbb{E}_{b}[\\mathcal{a}], \\mathcal{r}_{obs, n}),\n",
20 | "$$\n",
21 | "where $\\mathcal{r}_{obs, n}$ is the observed reward for validation example n.\n",
22 | "\n",
23 | "We define the model error vector as \n",
24 | "\n",
25 | "$$\n",
26 | "\\epsilon_{m}[\\mathcal{A}] = \\sum_{n_{a}=0}^{N_{obs, a}}RMSE(\\mathcal{r}_{pred,n}, \\mathcal{r}_{obs, n}),\n",
27 | "$$\n",
28 | "where $\\mathcal{r}_{pred, n}$ is the model's expected value of the reward for validation example n.\n",
29 | "\n",
30 | "\n",
31 | "This provides a benchmark with which to compare our model's RMSE, $\\epsilon_{m}[\\mathcal{A}]$ on the same prediction task on the validation set. If the condition $$\n",
32 | "\\sum_{a=0}^{A} \\frac{\\epsilon_{m}[\\mathcal{a}]}{\\epsilon_{b}[\\mathcal{a}]} < 1\n",
33 | "$$\n",
34 | "is met, we can be confident that our model is performing better than a simple multi-arm bandit model by conditioning on the context. For a simple \"higher-is-better\" score, we can define a contextual bandit model validation score $\\mathcal{S}$ as:\n",
35 | "$$\n",
36 | "\\mathcal{S} = \\sum_{a=0}^{A} 1 - \\frac{\\epsilon_{m}[\\mathcal{a}]}{\\epsilon_{b}[\\mathcal{a}]}\n",
37 | "$$\n",
38 | "\n",
39 | "Any value $\\mathcal{S} > 0$ is evidence for model convergence.\n",
40 | "\n",
41 | "## Example with Toy Data\n",
42 | "Using the same toy data used in the [toy problem notebook](toy_problem.ipynb), which we know converges, we can compute S and show that, for the converged model, $\\mathcal{S} > 0$."
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": 1,
48 | "metadata": {},
49 | "outputs": [
50 | {
51 | "data": {
52 | "text/html": [
53 | "\n",
54 | "\n",
67 | "
\n",
68 | " \n",
69 | " \n",
70 | " | \n",
71 | " age | \n",
72 | " ARPU | \n",
73 | " action | \n",
74 | " reward | \n",
75 | "
\n",
76 | " \n",
77 | " \n",
78 | " \n",
79 | " | 0 | \n",
80 | " 19.0 | \n",
81 | " 62.009640 | \n",
82 | " 2 | \n",
83 | " 0 | \n",
84 | "
\n",
85 | " \n",
86 | " | 1 | \n",
87 | " 44.0 | \n",
88 | " 46.434857 | \n",
89 | " 0 | \n",
90 | " 0 | \n",
91 | "
\n",
92 | " \n",
93 | " | 2 | \n",
94 | " 30.0 | \n",
95 | " 103.411680 | \n",
96 | " 0 | \n",
97 | " 10 | \n",
98 | "
\n",
99 | " \n",
100 | " | 3 | \n",
101 | " 23.0 | \n",
102 | " 92.682164 | \n",
103 | " 1 | \n",
104 | " 0 | \n",
105 | "
\n",
106 | " \n",
107 | " | 4 | \n",
108 | " 19.0 | \n",
109 | " 109.850754 | \n",
110 | " 1 | \n",
111 | " 0 | \n",
112 | "
\n",
113 | " \n",
114 | "
\n",
115 | "
"
116 | ],
117 | "text/plain": [
118 | " age ARPU action reward\n",
119 | "0 19.0 62.009640 2 0\n",
120 | "1 44.0 46.434857 0 0\n",
121 | "2 30.0 103.411680 0 10\n",
122 | "3 23.0 92.682164 1 0\n",
123 | "4 19.0 109.850754 1 0"
124 | ]
125 | },
126 | "execution_count": 1,
127 | "metadata": {},
128 | "output_type": "execute_result"
129 | }
130 | ],
131 | "source": [
132 | "import numpy as np\n",
133 | "import pandas as pd\n",
134 | "from random import random, randint\n",
135 | "import matplotlib.pyplot as plt\n",
136 | "import gc\n",
137 | "%config InlineBackend.figure_format='retina'\n",
138 | "##Generate Data\n",
139 | "\n",
140 | "from space_bandits.toy_problem import generate_dataframe\n",
141 | "\n",
142 | "df = generate_dataframe(4000)\n",
143 | "df.head()"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {},
149 | "source": [
150 | "We produce a dataset with randomly selected actions and 4000 rows.\n",
151 | "## Train/Validation Split\n",
152 | "We split the data into two equally-sized groups."
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": 2,
158 | "metadata": {},
159 | "outputs": [],
160 | "source": [
161 | "train = df.sample(frac=.5)\n",
162 | "val = df[~df.index.isin(train.index)]\n",
163 | "num_actions = len(train.action.unique())"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": 3,
169 | "metadata": {},
170 | "outputs": [],
171 | "source": [
172 | "#use this for computing error metric\n",
173 | "from sklearn.metrics import mean_squared_error"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {},
179 | "source": [
180 | "## Compute $\\epsilon_{b}[\\mathcal{A}]$\n",
181 | "We use the train set to compute $\\mathbb{E}_{b}[\\mathcal{A}]$ to get the benchmark error vector, $\\epsilon_{b}[\\mathcal{A}]$."
182 | ]
183 | },
184 | {
185 | "cell_type": "code",
186 | "execution_count": 4,
187 | "metadata": {},
188 | "outputs": [],
189 | "source": [
190 | "#compute benchmark expected value per action\n",
191 | "E_b = [train[train.action == a].reward.mean() for a in range(num_actions)]\n",
192 | "Err_b = []\n",
193 | "for a in range(num_actions):\n",
194 | " slc = val[val.action == a]\n",
195 | " y_pred = [E_b[a] for x in range(len(slc))]\n",
196 | " y_true = slc.reward\n",
197 | " error = mean_squared_error(y_pred, y_true)\n",
198 | " Err_b.append(error)\n",
199 | "Err_b = np.array(Err_b)"
200 | ]
201 | },
202 | {
203 | "cell_type": "code",
204 | "execution_count": 5,
205 | "metadata": {},
206 | "outputs": [
207 | {
208 | "data": {
209 | "text/plain": [
210 | "array([ 24.34257772, 52.31057004, 935.44289322])"
211 | ]
212 | },
213 | "execution_count": 5,
214 | "metadata": {},
215 | "output_type": "execute_result"
216 | }
217 | ],
218 | "source": [
219 | "Err_b"
220 | ]
221 | },
222 | {
223 | "cell_type": "markdown",
224 | "metadata": {},
225 | "source": [
226 | "## Fit the Model\n",
227 | "We fit the model on the training set."
228 | ]
229 | },
230 | {
231 | "cell_type": "code",
232 | "execution_count": 6,
233 | "metadata": {},
234 | "outputs": [],
235 | "source": [
236 | "from space_bandits import NeuralBandits\n",
237 | "\n",
238 | "model = NeuralBandits(num_actions, num_features=2, layer_sizes=[50,12], training_epochs=100)"
239 | ]
240 | },
241 | {
242 | "cell_type": "code",
243 | "execution_count": 7,
244 | "metadata": {},
245 | "outputs": [
246 | {
247 | "name": "stdout",
248 | "output_type": "stream",
249 | "text": [
250 | "Training neural_model-bnn for 100 steps...\n"
251 | ]
252 | }
253 | ],
254 | "source": [
255 | "model.fit(train[['age', 'ARPU']], train['action'], train['reward'])"
256 | ]
257 | },
258 | {
259 | "cell_type": "markdown",
260 | "metadata": {},
261 | "source": [
262 | "## Compute $\\epsilon_{m}[\\mathcal{A}]$\n",
263 | "We use the train set and compute the model expected rewards for each example in our validation set to get the model error vector, $\\epsilon_{m}[\\mathcal{A}]$."
264 | ]
265 | },
266 | {
267 | "cell_type": "code",
268 | "execution_count": 8,
269 | "metadata": {},
270 | "outputs": [
271 | {
272 | "data": {
273 | "text/html": [
274 | "\n",
275 | "\n",
288 | "
\n",
289 | " \n",
290 | " \n",
291 | " | \n",
292 | " age | \n",
293 | " ARPU | \n",
294 | " action | \n",
295 | " reward | \n",
296 | " 0 | \n",
297 | " 1 | \n",
298 | " 2 | \n",
299 | "
\n",
300 | " \n",
301 | " \n",
302 | " \n",
303 | " | 0 | \n",
304 | " 19.0 | \n",
305 | " 62.009640 | \n",
306 | " 2 | \n",
307 | " 0 | \n",
308 | " 11.256291 | \n",
309 | " 4.328109 | \n",
310 | " 3.595610 | \n",
311 | "
\n",
312 | " \n",
313 | " | 1 | \n",
314 | " 44.0 | \n",
315 | " 46.434857 | \n",
316 | " 0 | \n",
317 | " 0 | \n",
318 | " 2.604247 | \n",
319 | " 2.501696 | \n",
320 | " 20.869746 | \n",
321 | "
\n",
322 | " \n",
323 | " | 4 | \n",
324 | " 19.0 | \n",
325 | " 109.850754 | \n",
326 | " 1 | \n",
327 | " 0 | \n",
328 | " 9.536264 | \n",
329 | " 3.178807 | \n",
330 | " -0.042348 | \n",
331 | "
\n",
332 | " \n",
333 | " | 5 | \n",
334 | " 35.0 | \n",
335 | " 26.936240 | \n",
336 | " 0 | \n",
337 | " 0 | \n",
338 | " 2.332897 | \n",
339 | " 2.808232 | \n",
340 | " 21.452622 | \n",
341 | "
\n",
342 | " \n",
343 | " | 6 | \n",
344 | " 21.0 | \n",
345 | " 105.947998 | \n",
346 | " 0 | \n",
347 | " 10 | \n",
348 | " 9.119907 | \n",
349 | " 3.142819 | \n",
350 | " 0.376821 | \n",
351 | "
\n",
352 | " \n",
353 | "
\n",
354 | "
"
355 | ],
356 | "text/plain": [
357 | " age ARPU action reward 0 1 2\n",
358 | "0 19.0 62.009640 2 0 11.256291 4.328109 3.595610\n",
359 | "1 44.0 46.434857 0 0 2.604247 2.501696 20.869746\n",
360 | "4 19.0 109.850754 1 0 9.536264 3.178807 -0.042348\n",
361 | "5 35.0 26.936240 0 0 2.332897 2.808232 21.452622\n",
362 | "6 21.0 105.947998 0 10 9.119907 3.142819 0.376821"
363 | ]
364 | },
365 | "execution_count": 8,
366 | "metadata": {},
367 | "output_type": "execute_result"
368 | }
369 | ],
370 | "source": [
371 | "expected_values = model.expected_values(val[['age', 'ARPU']].values, scale=True)\n",
372 | "pred = pd.DataFrame()\n",
373 | "for a, vals in enumerate(expected_values):\n",
374 | " pred[a] = vals\n",
375 | "#expected reward values\n",
376 | "pred.index = val.index\n",
377 | "#add them to validation df\n",
378 | "val = pd.concat([val, pred], axis=1)\n",
379 | "val.head()"
380 | ]
381 | },
382 | {
383 | "cell_type": "code",
384 | "execution_count": 9,
385 | "metadata": {},
386 | "outputs": [],
387 | "source": [
388 | "#compute error vector\n",
389 | "Err_m = []\n",
390 | "for a in range(num_actions):\n",
391 | " slc = val[val.action == a]\n",
392 | " y_pred = slc[a]\n",
393 | " y_true = slc.reward\n",
394 | " error = mean_squared_error(y_pred, y_true)\n",
395 | " Err_m.append(error)\n",
396 | "Err_m = np.array(Err_m)"
397 | ]
398 | },
399 | {
400 | "cell_type": "code",
401 | "execution_count": 10,
402 | "metadata": {},
403 | "outputs": [
404 | {
405 | "data": {
406 | "text/plain": [
407 | "array([ 15.30096855, 53.23198686, 867.05886111])"
408 | ]
409 | },
410 | "execution_count": 10,
411 | "metadata": {},
412 | "output_type": "execute_result"
413 | }
414 | ],
415 | "source": [
416 | "Err_m"
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "metadata": {},
422 | "source": [
423 | "## Compute $\\mathcal{S}$"
424 | ]
425 | },
426 | {
427 | "cell_type": "code",
428 | "execution_count": 11,
429 | "metadata": {},
430 | "outputs": [
431 | {
432 | "name": "stdout",
433 | "output_type": "stream",
434 | "text": [
435 | "The contextual bandits model score is: 0.427\n"
436 | ]
437 | }
438 | ],
439 | "source": [
440 | "S = (1 - Err_m/Err_b).sum()\n",
441 | "print('The contextual bandits model score is: ', round(S, 3))"
442 | ]
443 | },
444 | {
445 | "cell_type": "markdown",
446 | "metadata": {},
447 | "source": [
448 | "## Conclusion\n",
449 | "As expected the model (which we know converges) yields a contextual bandits score $\\mathcal{S}>0$, which is evidence of convergence."
450 | ]
451 | }
452 | ],
453 | "metadata": {
454 | "kernelspec": {
455 | "display_name": "Python 3",
456 | "language": "python",
457 | "name": "python3"
458 | },
459 | "language_info": {
460 | "codemirror_mode": {
461 | "name": "ipython",
462 | "version": 3
463 | },
464 | "file_extension": ".py",
465 | "mimetype": "text/x-python",
466 | "name": "python",
467 | "nbconvert_exporter": "python",
468 | "pygments_lexer": "ipython3",
469 | "version": "3.6.8"
470 | }
471 | },
472 | "nbformat": 4,
473 | "nbformat_minor": 2
474 | }
475 |
--------------------------------------------------------------------------------
/space_bandits/neural_linear.py:
--------------------------------------------------------------------------------
1 | """Thompson Sampling with linear posterior over a learnt deep representation."""
2 |
3 | from __future__ import absolute_import
4 | from __future__ import division
5 | from __future__ import print_function
6 |
7 | import numpy as np
8 | np.seterr(all='warn')
9 |
10 | import warnings
11 |
12 | from scipy.stats import invgamma
13 |
14 | from .bandit_algorithm import BanditAlgorithm
15 | from .contextual_dataset import ContextualDataset
16 | from .neural_bandit_model import NeuralBanditModel
17 | import torch
18 |
19 | import multiprocessing
20 | import os
21 | import pickle
22 | import shutil
23 |
24 | #These functions help with multiprocessing random number generation.
25 | mus = None
26 | covs = None
27 |
28 | def load_model(path):
29 | with open(path, 'rb') as f:
30 | return pickle.load(f)
31 |
32 | def get_mn(i):
33 | """helper function to parallelize random number generation"""
34 | mu = mus[i]
35 | cov = covs[i]
36 | min_eig = np.min(np.real(np.linalg.eigvals(cov)))
37 | if min_eig < 0:
38 | cov -= 10*min_eig * np.eye(*cov.shape)
39 | return np.random.multivariate_normal(mu, cov)
40 |
41 | def parallelize_multivar(mus, covs, n_threads=-1):
42 | """parallelizes mn computation"""
43 | if n_threads == -1:
44 | try:
45 | cpus = multiprocessing.cpu_count() - 1
46 | except NotImplementedError:
47 | cpus = 2 # arbitrary default
48 | else:
49 | cpus = n_threads
50 |
51 | with multiprocessing.Pool(processes=cpus) as pool:
52 | samples = pool.map(get_mn, range(len(mus)))
53 | return samples
54 |
55 |
56 | class NeuralBandits(BanditAlgorithm):
57 | """Full Bayesian linear regression on the last layer of a deep neural net."""
58 |
59 | def __init__(
60 | self,
61 | num_actions,
62 | num_features,
63 | name='neural_model',
64 | do_scaling=True,
65 | init_scale=0.3,
66 | activation='relu',
67 | verbose=True,
68 | optimizer='RMS',
69 | layer_sizes=[50],
70 | batch_size=512,
71 | activate_decay=True,
72 | initial_lr=0.1,
73 | max_grad_norm=5.0,
74 | show_training=False,
75 | freq_summary=1000,
76 | buffer_s=-1,
77 | initial_pulls=100,
78 | reset_lr=True,
79 | lr_decay_rate=0.5,
80 | training_freq=1,
81 | training_freq_network=50,
82 | training_epochs=100,
83 | memory_size=-1,
84 | a0=6,
85 | b0=6,
86 | lambda_prior=0.25,
87 | ):
88 | """
89 | A "NeuralLinear" Deep Bayesian contextual bandits model.
90 |
91 | num_actions (int): the number of actions in problem
92 |
93 | num_features (int): the length of context vector, a.k.a. the number of features
94 |
95 | name (string): name for this model instance (default 'neural_model')
96 |
97 | do_scaling (bool): whether to automatically scale features (default True)
98 |
99 | init_scale (float): variance for neural network weights initialization (default 0.3)
100 |
101 | activation (string): activation function for neural network layers (default 'relu')
102 |
103 | verbose (bool): whether to print reports on training steps (default True)
104 |
105 | layer_sizes (list of integers): defines neural network architecture: n_layers = len(layer_sizes), value is per-layer width. (default [50])
106 |
107 | batch_size (integer): batch size for neural network training (default 512)
108 |
109 | activate_decay (bool): whether to use learning rate decay (default True),
110 |
111 | initial_lr (float): initial learning rate for neural network training (default 0.1)
112 |
113 | max_grad_norm (float): maximum gradient value for gradient clipping (default 5.0)
114 |
115 | show_training (bool): whether to show details of neural network training
116 |
117 | freq_summary (int): summary output frequency in number of steps (default 1000)
118 |
119 | buffer_s (int): buffer size for retained examples (default -1)
120 |
121 | initial_pulls (int): number of random pulls before greedy behavior (default 100),
122 |
123 | reset_lr (bool) = whether to reset learning rate on each nn training (default True),
124 |
125 | lr_decay_rate (float): learning rate decay for nn updates (default 0.5)
126 |
127 | training_freq (int): frequency for updates to bayesian linear regressor (default 1)
128 |
129 | training_freq_network (int): frequency of neural network re-trainings (default 50)
130 |
131 | training_epochs (int): number of epochs in each neural network re-training (default 100)
132 |
133 | a0 (int): initial alpha value (default 6)
134 |
135 | b0 (int): initial beta_0 value (default 6)
136 |
137 | lambda_prior (float): lambda prior parameter(default 0.25)
138 | """
139 | self.hparams = {
140 | 'num_actions':num_actions,
141 | 'context_dim':num_features,
142 | 'name':name,
143 | 'init_scale':init_scale,
144 | 'activation':activation,
145 | 'verbose':verbose,
146 | 'optimizer':optimizer,
147 | 'layer_sizes':layer_sizes,
148 | 'batch_size':batch_size,
149 | 'activate_decay':activate_decay,
150 | 'initial_lr':initial_lr,
151 | 'max_grad_norm':max_grad_norm,
152 | 'show_training':show_training,
153 | 'freq_summary':freq_summary,
154 | 'buffer_s':buffer_s,
155 | 'initial_pulls':initial_pulls,
156 | 'reset_lr':reset_lr,
157 | 'lr_decay_rate':lr_decay_rate,
158 | 'training_freq':training_freq,
159 | 'training_freq_network':training_freq_network,
160 | 'training_epochs':training_epochs,
161 | 'memory_size':memory_size,
162 | 'a0':a0,
163 | 'b0':b0,
164 | 'lambda_prior':lambda_prior
165 | }
166 | self.do_scaling = do_scaling
167 | self.name = name
168 | self.latent_dim = self.hparams['layer_sizes'][-1]
169 | self.num_actions = self.hparams['num_actions']
170 | self.context_dim = self.hparams['context_dim']
171 | self.initial_pulls = self.hparams['initial_pulls']
172 | self.reset_lr = self.hparams['reset_lr']
173 |
174 | self.master_params = dict()
175 |
176 | # Gaussian prior for each beta_i
177 | self._lambda_prior = self.hparams['lambda_prior']
178 |
179 | self.mu = [
180 | np.zeros(self.latent_dim)
181 | for _ in range(self.hparams['num_actions'])
182 | ]
183 |
184 | self.cov = [(1.0 / self.lambda_prior) * np.eye(self.latent_dim)
185 | for _ in range(self.hparams['num_actions'])]
186 |
187 | self.precision = [
188 | self.lambda_prior * np.eye(self.latent_dim)
189 | for _ in range(self.hparams['num_actions'])
190 | ]
191 |
192 | # Inverse Gamma prior for each sigma2_i
193 | self._a0 = self.hparams['a0']
194 | self._b0 = self.hparams['b0']
195 |
196 | self.a = [self._a0 for _ in range(self.hparams['num_actions'])]
197 | self.b = [self._b0 for _ in range(self.hparams['num_actions'])]
198 |
199 | # Regression and NN Update Frequency
200 | self.update_freq_lr = self.hparams['training_freq']
201 | self.update_freq_nn = self.hparams['training_freq_network']
202 |
203 | self.t = 0
204 | self.optimizer_n = optimizer
205 |
206 | self.num_epochs = self.hparams['training_epochs']
207 |
208 | memory_size = self.hparams['memory_size']
209 |
210 | self.data_h = ContextualDataset(
211 | self.hparams['context_dim'],
212 | self.hparams['num_actions'],
213 | intercept=False,
214 | memory_size=memory_size
215 | )
216 |
217 | self.latent_h = ContextualDataset(
218 | self.latent_dim,
219 | self.hparams['num_actions'],
220 | intercept=False,
221 | memory_size=memory_size
222 | )
223 |
224 | self.bnn = NeuralBanditModel(optimizer, self.hparams, f'{name}-bnn')
225 |
226 | def get_representation(self, context):
227 | """
228 | Returns the latent feature vector from the neural network.
229 | This vector is called z in the Google Brain paper.
230 | """
231 | if not isinstance(context, torch.Tensor):
232 | c = torch.tensor(context).float()
233 | else:
234 | c = context.float()
235 | z = self.bnn.get_representation(c)
236 | return z
237 |
238 | def expected_values(self, context, scale=False):
239 | """
240 | Computes expected values from context. Does not consider uncertainty.
241 | Args:
242 | context: Context for which the action need to be chosen.
243 | Returns:
244 | expected reward vector.
245 | """
246 | if scale:
247 | context = self.data_h.scale_contexts(contexts=context)
248 |
249 | # Compute last-layer representation for the current context
250 | z_context = self.get_representation(context).numpy()
251 |
252 | # Compute sampled expected values, intercept is last component of beta
253 | vals = [
254 | np.dot(self.mu[i], z_context.T)
255 | for i in range(self.hparams['num_actions'])
256 | ]
257 | return np.array(vals)
258 |
259 | def _sample(self, context, parallelize=False, n_threads=-1):
260 | # Sample sigma2, and beta conditional on sigma2
261 | n_rows = len(context)
262 | d = self.mu[0].shape[0]
263 | a_projected = np.repeat(np.array(self.a)[np.newaxis, :], n_rows, axis=0)
264 | sigma2_s = self.b * invgamma.rvs(a_projected)
265 | if n_rows == 1:
266 | sigma2_s = sigma2_s.reshape(1, -1)
267 | beta_s = []
268 | try:
269 | for i in range(self.hparams['num_actions']):
270 | global mus
271 | global covs
272 | mus = np.repeat(self.mu[i][np.newaxis, :], n_rows, axis=0)
273 | s2s = sigma2_s[:, i]
274 | rep = np.repeat(s2s[:, np.newaxis], d, axis=1)
275 | rep = np.repeat(rep[:, :, np.newaxis], d, axis=2)
276 | covs = np.repeat(self.cov[i][np.newaxis, :, :], n_rows, axis=0)
277 | covs = rep * covs
278 | if parallelize:
279 | multivariates = parallelize_multivar(mus, covs, n_threads=n_threads)
280 | else:
281 | multivariates = [np.random.multivariate_normal(mus[j], covs[j]) for j in range(n_rows)]
282 | beta_s.append(multivariates)
283 | except np.linalg.LinAlgError as e:
284 | # Sampling could fail if covariance is not positive definite
285 | # Todo: Fix This
286 | print('Exception when sampling from {}.'.format(self.name))
287 | print('Details: {} | {}.'.format(e.message, e.args))
288 | for i in range(self.hparams['num_actions']):
289 | multivariates = [np.random.multivariate_normal(np.zeros((d)), np.eye(d)) for j in range(n_rows)]
290 | beta_s.append(multivariates)
291 | beta_s = np.array(beta_s)
292 |
293 | # Compute last-layer representation for the current context
294 | z_context = self.get_representation(context).numpy()
295 |
296 | # Apply Thompson Sampling
297 | vals = [
298 | (beta_s[i, :, :] * z_context).sum(axis=-1)
299 | for i in range(self.hparams['num_actions'])
300 | ]
301 | return np.array(vals)
302 |
303 | def action(self, context):
304 | """Samples beta's from posterior, and chooses best action accordingly."""
305 | # Round robin until each action has been selected "initial_pulls" times
306 | if self.t < self.num_actions * self.initial_pulls:
307 | return self.t % self.num_actions
308 | else:
309 | context = context.reshape(-1, self.hparams['context_dim'])
310 | if self.do_scaling:
311 | context = self.data_h.scale_contexts(contexts=context)
312 | vals = self._sample(context)
313 | return np.argmax(vals)
314 |
315 | def update(self, context, action, reward):
316 | """Updates the posterior using linear bayesian regression formula."""
317 | self.t += 1
318 | self.data_h.add(context, action, reward)
319 | c = context.reshape((1, self.context_dim))
320 | z_context = self.get_representation(c)
321 | self.latent_h.add(z_context, action, reward)
322 | # Retrain the network on the original data (data_h)
323 | if self.t % self.update_freq_nn == 0:
324 | self._retrain_nn()
325 |
326 | if self.t % self.update_freq_lr == 0:
327 | self._update_actions()
328 |
329 | def _retrain_nn(self):
330 | """Retrain the network on original data (data_h)"""
331 | if self.reset_lr:
332 | self.bnn.assign_lr()
333 |
334 | #uncomment following lines for better stuff.
335 | #steps = round(self.num_epochs * (len(self.data_h)/self.hparams['batch_size']))
336 | #print(f"training for {steps} steps.")
337 | self.bnn.train(self.data_h, self.num_epochs)
338 | self._replace_latent_h()
339 |
340 | def _replace_latent_h(self):
341 | # Update the latent representation of every datapoint collected so far
342 | if self.do_scaling:
343 | self.data_h.scale_contexts()
344 | ctx = self.data_h.get_contexts(scaled=self.do_scaling)
345 | new_z = self.get_representation(ctx)
346 |
347 | self.latent_h._replace_data(contexts=new_z)
348 |
349 | def _update_actions(self):
350 | """
351 | Update the Bayesian Linear Regression on
352 | stored latent variables.
353 | """
354 |
355 | # Find all the actions to update
356 | actions_to_update = self.latent_h.actions
357 |
358 | for action_v in np.unique(actions_to_update):
359 |
360 | # Update action posterior with formulas: \beta | z,y ~ N(mu_q, cov_q)
361 | z, y = self.latent_h.get_data(action_v)
362 | z = z.numpy()
363 | y = y.numpy()
364 |
365 | # The algorithm could be improved with sequential formulas (cheaper)
366 | s = np.dot(z.T, z)
367 |
368 | # Some terms are removed as we assume prior mu_0 = 0.
369 | precision_a = s + self.lambda_prior * np.eye(self.latent_dim)
370 | cov_a = np.linalg.inv(precision_a)
371 | mu_a = np.dot(cov_a, np.dot(z.T, y))
372 |
373 | # Inverse Gamma posterior update
374 | a_post = self.a0 + z.shape[0] / 2.0
375 | b_upd = 0.5 * np.dot(y.T, y)
376 | b_upd -= 0.5 * np.dot(mu_a.T, np.dot(precision_a, mu_a))
377 | b_post = self.b0 + b_upd
378 |
379 | # Store new posterior distributions
380 | self.mu[action_v] = mu_a
381 | self.cov[action_v] = cov_a
382 | self.precision[action_v] = precision_a
383 | self.a[action_v] = a_post
384 | self.b[action_v] = b_post
385 |
386 | def fit(self, contexts, actions, rewards):
387 | """Inputs bulk data for training.
388 | Args:
389 | contexts: Set of observed contexts.
390 | actions: Corresponding list of actions.
391 | rewards: Corresponding list of rewards.
392 | """
393 | data_length = len(rewards)
394 | self.data_h._ingest_data(contexts, actions, rewards)
395 | #create latent representations of data
396 | self._replace_latent_h()
397 | self.latent_h.actions = self.data_h.actions.copy()
398 | self.latent_h.rewards = self.data_h.rewards
399 | #update count
400 | self.t += data_length
401 | #update posterior on ingested data
402 | self._retrain_nn()
403 | self._update_actions()
404 |
405 |
406 | def predict(self, contexts, thompson=True, parallelize=True, n_threads=-1):
407 | """Takes a list or array-like of contexts and batch predicts on them"""
408 | contexts = contexts.reshape(-1, self.hparams['context_dim'])
409 | if self.do_scaling:
410 | contexts = self.data_h.scale_contexts(contexts=contexts)
411 |
412 | if thompson:
413 | reward_matrix = self._sample(contexts, parallelize=parallelize, n_threads=n_threads)
414 | else:
415 | reward_matrix = self.expected_values(contexts)
416 | return np.argmax(reward_matrix, axis=0)
417 |
418 | def save(self, path):
419 | """saves model to path"""
420 | with open(path, 'wb') as f:
421 | pickle.dump(self, f)
422 |
423 | @property
424 | def a0(self):
425 | return self._a0
426 |
427 | @property
428 | def b0(self):
429 | return self._b0
430 |
431 | @property
432 | def lambda_prior(self):
433 | return self._lambda_prior
434 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------