Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AllenDowney
GitHub Repository: AllenDowney/bayesian-analysis-recipes
Path: blob/master/models/feedforward.py
411 views
1
from .__init__ import BayesianModel
2
import theano
3
import theano.tensor as tt
4
import numpy as np
5
import pymc3 as pm
6
7
8
class ForestCoverModel(BayesianModel):
9
10
def __init__(self, n_hidden):
11
super(ForestCoverModel, self).__init__()
12
self.n_hidden = n_hidden
13
14
def create_model(self, X=None, y=None):
15
if X:
16
num_samples, self.num_pred = X.shape
17
18
if y:
19
num_samples, self.num_out = Y.shape
20
21
model_input = theano.shared(np.zeros(shape=(1, self.num_pred)))
22
model_output = theano.shared(np.zeros(self.num_out))
23
24
self.shared_vars = {
25
'model_input': model_input,
26
'model_output': model_output
27
}
28
29
with pm.Model() as model:
30
# Define weights
31
weights_1 = pm.Normal('w_1', mu=0, sd=1,
32
shape=(self.num_pred, self.n_hidden))
33
weights_2 = pm.Normal('w_2', mu=0, sd=1,
34
shape=(self.n_hidden, self.n_hidden))
35
weights_out = pm.Normal('w_out', mu=0, sd=1,
36
shape=(self.n_hidden, self.num_outs))
37
38
# Define activations
39
acts_1 = tt.tanh(tt.dot(model_input, weights_1))
40
acts_2 = tt.tanh(tt.dot(acts_1, weights_2))
41
acts_out = tt.nnet.softmax(tt.dot(acts_2, weights_out)) # noqa
42
43
# Define likelihood
44
out = pm.Multinomial('likelihood', n=1, p=acts_out,
45
observed=model_output)
46
47
return model
48
49
50
def fit(self, X, y, n=200000, batch_size=10):
51
"""
52
Train the Bayesian NN model.
53
"""
54
num_samples, self.num_pred = X.shape
55
56
if self.cached_model is None:
57
self.cached_model = self.create_model()
58
59
with self.cached_model:
60
minibatches = {
61
self.shared_vars['model_input']: pm.Minibatch(X, batch_size=batch_size),
62
self.shared_vars['model_output']: pm.Minibatch(y, batch_size=batch_size),
63
}
64
self._inference(minibatches, n)
65
66
return self
67
68
69
70
71