8 print(
"Please install theano: pip3 install theano")
13 from collections
import namedtuple
18 State class for proper handling of parameters and data during function calls. This is a very brief theano example.
21 def __init__(self, x=None, y=None, params=None, cost=None, updates=None, train_function=None, eval_function=None):
23 Constructor of the State class
45 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
47 x = theano.tensor.matrix(
'x')
48 y = theano.tensor.vector(
'y', dtype=
'float32')
53 n_in = number_of_features
55 rng = numpy.random.RandomState(1234)
56 w_values = numpy.asarray(
58 low=-numpy.sqrt(6. / (n_in + n_out)),
59 high=numpy.sqrt(6. / (n_in + n_out)),
62 dtype=theano.config.floatX
66 w = theano.shared(value=w_values, name=
'W', borrow=
True)
68 b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
69 b = theano.shared(value=b_values, name=
'b', borrow=
True)
71 activation = theano.tensor.nnet.sigmoid
73 output = activation(theano.tensor.dot(x, w) + b)
75 cost = theano.tensor.nnet.binary_crossentropy(output.T, y).mean()
79 grad_params = [theano.tensor.grad(cost, param)
for param
in params]
81 updates = [(param, param - learning_rate * gparam)
for param, gparam
in zip(params, grad_params)]
83 train_function = theano.function(
89 eval_function = theano.function(
94 return State(x, y, params, cost, updates, train_function, eval_function)
97 def feature_importance(state):
99 Return a list containing the feature importances
105 state =
State(eval_function=obj[0])
110 result = state.eval_function(X)
111 return np.require(result, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
114 def begin_fit(state, Xvalid, Svalid, yvalid, wvalid):
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))
127 return [state.eval_function]