Belle II Software  release-05-01-25
theano.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*
3 
4 try:
5  import theano
6  import theano.tensor
7 except ImportError:
8  print("Please install theano: pip3 install theano")
9  import sys
10  sys.exit(1)
11 
12 import numpy
13 from collections import namedtuple
14 
15 
16 class State(object):
17  """
18  State class for proper handling of parameters and data during function calls. This is a very brief theano example.
19  """
20 
21  def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None):
22  """
23  Constructor of the State class
24  """
25  # TODO: make serializable with __getstate__(), __setstate__()
26 
27  self.x = x
28 
29  self.y = y
30 
31 
32  self.params = params
33 
34  self.cost = cost
35 
36 
37  self.updates = updates
38 
39 
40  self.train_function = train_function
41 
42  self.eval_function = eval_function
43 
44 
45 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
46 
47  x = theano.tensor.matrix('x')
48  y = theano.tensor.vector('y', dtype='float32')
49 
50  # learning_rate = parameters.get('learning_rate', 0.1)
51  learning_rate = 0.1
52 
53  n_in = number_of_features
54  n_out = 1
55  rng = numpy.random.RandomState(1234)
56  w_values = numpy.asarray(
57  rng.uniform(
58  low=-numpy.sqrt(6. / (n_in + n_out)),
59  high=numpy.sqrt(6. / (n_in + n_out)),
60  size=(n_in, n_out)
61  ),
62  dtype=theano.config.floatX
63  )
64 
65  w_values *= 4
66  w = theano.shared(value=w_values, name='W', borrow=True)
67 
68  b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
69  b = theano.shared(value=b_values, name='b', borrow=True)
70 
71  activation = theano.tensor.nnet.sigmoid
72 
73  output = activation(theano.tensor.dot(x, w) + b)
74 
75  cost = theano.tensor.nnet.binary_crossentropy(output.T, y).mean()
76 
77  params = [w, b]
78 
79  grad_params = [theano.tensor.grad(cost, param) for param in params]
80 
81  updates = [(param, param - learning_rate * gparam) for param, gparam in zip(params, grad_params)]
82 
83  train_function = theano.function(
84  inputs=[x, y],
85  outputs=cost,
86  updates=updates
87  )
88 
89  eval_function = theano.function(
90  inputs=[x],
91  outputs=output
92  )
93 
94  return State(x, y, params, cost, updates, train_function, eval_function)
95 
96 
97 def feature_importance(state):
98  """
99  Return a list containing the feature importances
100  """
101  return []
102 
103 
104 def load(obj):
105  state = State(eval_function=obj[0])
106  return state
107 
108 
109 def apply(state, X):
110  result = state.eval_function(X)
111  return np.require(result, dtype=np.float32, requirements=['A', 'W', 'C', 'O'])
112 
113 
114 def begin_fit(state, Xvalid, Svalid, yvalid, wvalid):
115  return state
116 
117 
118 def partial_fit(state, X, S, y, w, epoch):
119  avg_cost = state.train_function(X, y) / len(y)
120  print("Epoch:", '%04d' % (epoch), "cost=", "{:.9f}".format(avg_cost))
121  return True
122 
123 
124 def end_fit(state):
125  # FIXME: this might not work as intended
126  # a better method can be found at: http://deeplearning.net/software/theano/tutorial/loading_and_saving.html
127  return [state.eval_function]
basf2_mva_python_interface.theano.State.x
x
theano shared variable x
Definition: theano.py:27
basf2_mva_python_interface.theano.State.train_function
train_function
theano function for training
Definition: theano.py:40
basf2_mva_python_interface.theano.State
Definition: theano.py:16
basf2_mva_python_interface.theano.State.params
params
model params
Definition: theano.py:32
basf2_mva_python_interface.theano.State.__init__
def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None)
Definition: theano.py:21
basf2_mva_python_interface.theano.State.updates
updates
model grad updates
Definition: theano.py:37
basf2_mva_python_interface.theano.State.cost
cost
model cost
Definition: theano.py:34
basf2_mva_python_interface.theano.State.eval_function
eval_function
theano function for evaluation
Definition: theano.py:42
basf2_mva_python_interface.theano.State.y
y
theano shared variable y
Definition: theano.py:29