How to make Keras use Tensorflow backend in Anaconda?

Tai Christian picture Tai Christian · Apr 10, 2017 · Viewed 29.8k times · Source

I have install tensorflow-gpu in my Anaconda environment. They both work well.

Now I am trying to install Keras with Tensorflow backend. According to the instruction I just run:

pip install keras

But it doesn't install keras, then I tried:

conda install -c conda-forge keras=2.0.2

Then I am now able import keras in python. But the problem is, it always use the Theano backend. I am trying to change this, but not knowing how to do it.

I also tried edit the file ~/.keras, but actually default backend was tensorflow already.

Please help.. Thank you so much!

Answer

Nehal J Wani picture Nehal J Wani · Apr 10, 2017

This happens because the keras conda-forge package puts a file in ${CONDA_PREFIX}/etc/conda/activate.d/keras_activate.sh, which sets the environment variable KERAS_BACKEND

(root) [root@starlabs ~]# cat $CONDA_PREFIX/etc/conda/activate.d/keras_activate.sh
#!/bin/bash
if [ "$(uname)" == "Darwin" ]
then
    # for Mac OSX
    export KERAS_BACKEND=tensorflow
elif [ "$(uname)" == "Linux" ]
then
    # for Linux
    export KERAS_BACKEND=theano
fi

As you can see from the file, in Linux, it sets the value to 'theano' and according to the official docs:

the environment variable KERAS_BACKEND will override what is defined in your config file

To work around this, you can either edit this file and change 'theano' to 'tensorflow' (which would probably get overwritten on reinstall or on changing environments) or, do the following:

export KERAS_BACKEND=tensorflow
python /path/to/python/program.py