Model visualization

Keras provides utility functions to plot a Keras model (using graphviz).

This will plot a graph of the model and save it to a file:

  1. from keras.utils import plot_model
  2. plot_model(model, to_file='model.png')

plot_model takes four optional arguments:

  • show_shapes (defaults to False) controls whether output shapes are shown in the graph.
  • show_layer_names (defaults to True) controls whether layer names are shown in the graph.
  • expand_nested (defaults to False) controls whether to expand nested models into clusters in the graph.
  • dpi (defaults to 96) controls image dpi.

You can also directly obtain the pydot.Graph object and render it yourself,for example to show it in an ipython notebook :

  1. from IPython.display import SVG
  2. from keras.utils import model_to_dot
  3. SVG(model_to_dot(model).create(prog='dot', format='svg'))

Training history visualization

The fit() method on a Keras Model returns a History object. The History.history attribute is a dictionary recording training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable). Here is a simple example using matplotlib to generate loss & accuracy plots for training & validation:

  1. import matplotlib.pyplot as plt
  2. history = model.fit(x, y, validation_split=0.25, epochs=50, batch_size=16, verbose=1)
  3. # Plot training & validation accuracy values
  4. plt.plot(history.history['acc'])
  5. plt.plot(history.history['val_acc'])
  6. plt.title('Model accuracy')
  7. plt.ylabel('Accuracy')
  8. plt.xlabel('Epoch')
  9. plt.legend(['Train', 'Test'], loc='upper left')
  10. plt.show()
  11. # Plot training & validation loss values
  12. plt.plot(history.history['loss'])
  13. plt.plot(history.history['val_loss'])
  14. plt.title('Model loss')
  15. plt.ylabel('Loss')
  16. plt.xlabel('Epoch')
  17. plt.legend(['Train', 'Test'], loc='upper left')
  18. plt.show()