15 print(
"Please install theano: pip3 install theano")
24 State class for proper handling of parameters and data during function calls. This
is a very brief theano example.
27 def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None):
29 Constructor of the State class
51def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
53 x = theano.tensor.matrix(
'x')
54 y = theano.tensor.vector(
'y', dtype=
'float32')
59 n_in = number_of_features
61 rng = numpy.random.RandomState(1234)
62 w_values = numpy.asarray(
64 low=-numpy.sqrt(6. / (n_in + n_out)),
65 high=numpy.sqrt(6. / (n_in + n_out)),
68 dtype=theano.config.floatX
72 w = theano.shared(value=w_values, name=
'W', borrow=
True)
74 b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
75 b = theano.shared(value=b_values, name=
'b', borrow=
True)
77 activation = theano.tensor.nnet.sigmoid
79 output = activation(theano.tensor.dot(x, w) + b)
81 cost = theano.tensor.nnet.binary_crossentropy(output.T, y).mean()
85 grad_params = [theano.tensor.grad(cost, param)
for param
in params]
87 updates = [(param, param - learning_rate * gparam)
for param, gparam
in zip(params, grad_params)]
89 train_function = theano.function(
95 eval_function = theano.function(
100 return State(x, y, params, cost, updates, train_function, eval_function)
103def feature_importance(state):
105 Return a list containing the feature importances
111 state =
State(eval_function=obj[0])
116 result = state.eval_function(X)
117 return numpy.require(result, dtype=numpy.float32, requirements=[
'A',
'W',
'C',
'O'])
120def begin_fit(state, Xvalid, Svalid, yvalid, wvalid, nBatches):
124def partial_fit(state, X, S, y, w, epoch, batch):
125 avg_cost = state.train_function(X, y) / len(y)
126 print(
"Epoch:", f
'{int(epoch):04}',
"Batch:", f
'{int(batch):04}',
"cost=", f
"{avg_cost:.9f}")
133 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