16 print(
"Please install theano: pip3 install theano")
25 State class for proper handling of parameters and data during function calls. This is a very brief theano example.
28 def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None):
30 Constructor of the State class
52 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
54 x = theano.tensor.matrix(
'x')
55 y = theano.tensor.vector(
'y', dtype=
'float32')
60 n_in = number_of_features
62 rng = numpy.random.RandomState(1234)
63 w_values = numpy.asarray(
65 low=-numpy.sqrt(6. / (n_in + n_out)),
66 high=numpy.sqrt(6. / (n_in + n_out)),
69 dtype=theano.config.floatX
73 w = theano.shared(value=w_values, name=
'W', borrow=
True)
75 b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
76 b = theano.shared(value=b_values, name=
'b', borrow=
True)
78 activation = theano.tensor.nnet.sigmoid
80 output = activation(theano.tensor.dot(x, w) + b)
82 cost = theano.tensor.nnet.binary_crossentropy(output.T, y).mean()
86 grad_params = [theano.tensor.grad(cost, param)
for param
in params]
88 updates = [(param, param - learning_rate * gparam)
for param, gparam
in zip(params, grad_params)]
90 train_function = theano.function(
96 eval_function = theano.function(
101 return State(x, y, params, cost, updates, train_function, eval_function)
104 def feature_importance(state):
106 Return a list containing the feature importances
112 state =
State(eval_function=obj[0])
117 result = state.eval_function(X)
118 return numpy.require(result, dtype=numpy.float32, requirements=[
'A',
'W',
'C',
'O'])
121 def begin_fit(state, Xvalid, Svalid, yvalid, wvalid):
125 def partial_fit(state, X, S, y, w, epoch):
126 avg_cost = state.train_function(X, y) / len(y)
127 print(
"Epoch:",
'%04d' % (epoch),
"cost=",
"{:.9f}".format(avg_cost))
134 return [state.eval_function]
updates
model grad updates
y
theano shared variable y
eval_function
theano function for evaluation
x
theano shared variable x
def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None)
train_function
theano function for training