Logo ROOT   6.16/01
Reference Guide
GenerateModel.py
Go to the documentation of this file.
1#!/usr/bin/env python
2
3from keras.models import Sequential
4from keras.layers.core import Dense, Activation
5from keras.regularizers import l2
6from keras.optimizers import SGD
7
8# Setup the model here
9num_input_nodes = 4
10num_output_nodes = 2
11num_hidden_layers = 1
12nodes_hidden_layer = 64
13l2_val = 1e-5
14
15model = Sequential()
16
17# Hidden layer 1
18# NOTE: Number of input nodes need to be defined in this layer
19model.add(Dense(nodes_hidden_layer, activation='relu', W_regularizer=l2(l2_val), input_dim=num_input_nodes))
20
21# Hidden layer 2 to num_hidden_layers
22# NOTE: Here, you can do what you want
23for k in range(num_hidden_layers-1):
24 model.add(Dense(nodes_hidden_layer, activation='relu', W_regularizer=l2(l2_val)))
25
26# Ouput layer
27# NOTE: Use following output types for the different tasks
28# Binary classification: 2 output nodes with 'softmax' activation
29# Regression: 1 output with any activation ('linear' recommended)
30# Multiclass classification: (number of classes) output nodes with 'softmax' activation
31model.add(Dense(num_output_nodes, activation='softmax'))
32
33# Compile model
34# NOTE: Use following settings for the different tasks
35# Any classification: 'categorical_crossentropy' is recommended loss function
36# Regression: 'mean_squared_error' is recommended loss function
37model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01), metrics=['accuracy',])
38
39# Save model
40model.save('model.h5')
41
42# Additional information about the model
43# NOTE: This is not needed to run the model
44
45# Print summary
46model.summary()
47
48# Visualize model as graph
49try:
50 from keras.utils.visualize_util import plot
51 plot(model, to_file='model.png', show_shapes=True)
52except:
53 print('[INFO] Failed to make model plot')