Dynamically switch Keras backend in Jupyter notebooks

Recently, I was looking for a way to dynamically switch Keras backend between Theano and TensorFlow while working with Jupyter notebooks; I thought that there must be a way to work with multiple Keras configuration files, but this proved not to be the case.

My issue was that, while I am mainly working with Theano, I wanted a quick and painless way to start a Jupyter notebook with TensorFlow backend instead. And while Keras provides the KERAS_BACKEND environment variable, there is still the issue of image dimension ordering, which is handled differently in Theano and TensorFlow, and cannot be set with a command line flag like KERAS_BACKEND; and image dimension ordering is already the source of endless confusion and frustration, especially among beginners (check the “A quick note on image_dim_ordering” section in this post).

Recalling the profiles functionality of IPython, my first thought was to build two different profiles for use with Theano and TensorFlow respectively, but, as I was soon to discover, the profiles functionality did not survive the migration from IPython to Jupyter.

Eventually, I figured out the solution, employing the startup files functionality of IPython which, surprisingly enough, works along with Jupyter, too. So, here is a complete demonstration of the issue and the solution.

As I said, in my situation Keras is by default configured to work with Theano, so here is the content of my ~/.keras/keras.json file:

but, as shown below, the image dimension ordering is still set to 'th' (for Theano):

The solution is to write a small Python script keras_init.py that will always run at Jupyter startup; it will check the backend and, if it is set to TensorFlow, it will configure accordingly the image dimension ordering:

Christos - Iraklis is one of our resident Data Scientists. He holds advanced graduate degrees in applied mathematics, engineering, and computing. He has been awarded both Chartered Engineer and Chartered Manager status in the UK, as well as Master status in Kaggle.com due to "consistent and stellar results" in predictive analytics contests.

The idea was exactly to avoid the necessity of carrying such “preamble” code snippets in each & every notebook. And your suggestion still needs some lines in order to address the image ordering parameter…