Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch Backend with Keras (from TensorFlow to Theano)

People also ask

How do I change Keras backend from TensorFlow to Theano?

keras directory will be created in the user's home directory. To observe whether or not it has been created, run the following command from your home directory (the -a allows you to see hidden files and directories). Then edit the file to make the config changes you referenced to change the backend engine to Theano.

Does Keras still support Theano?

Back then he stated that “Theano support will continue for as long as Keras exists, because Keras is meant as an interface rather than as an end-to-end framework”.


Create a .keras (note the . in front) folder in you home directory and put the keras.json file there.

For example, /home/DaniPaniz/.keras/keras.json (or ~/.keras/keras.json in short) if you are on a UNIX like system (MacOS X, Linux, *BSD). On Windows you want to create the folder %USERPROFILE%/.keras and put the JSON file there.

Alternatively, you can also set the environment variable KERAS_BACKEND:

KERAS_BACKEND=theano python mymodel.py

In case you want to change the config permanently, the json is available here: ~/.keras/keras.json and you can change the backend.

To do this dynamically in python 2.7 you can run:

from keras import backend as K
import os

def set_keras_backend(backend):

    if K.backend() != backend:
        os.environ['KERAS_BACKEND'] = backend
        reload(K)
        assert K.backend() == backend

set_keras_backend("theano")

I had an issue where I could not from keras import backend at all until I set the backend to theano. The provided answers should work if you can import backend, but if not, just use:

import os
os.environ['KERAS_BACKEND'] = 'theano'
import keras as ks
# Using Theano backend.

In windows, you need to find .keras folder in your C drive. Most probably, it will be somewhere in C:/users/username/. There you will find .keras folder, it contains a json file, keras.json, open it. You will see:

{
“backend”: “tensorflow”,
“floatx”: “float32”,
“epsilon”: 1e-07
}

more or less. replace 'tensorflow' with 'theano'. and save the file.


If you're using windows you can run from command line:

set "KERAS_BACKEND=theano"


from keras import backend as K
from os import environ

# user defined function to change keras backend
def set_keras_backend(backend):
    if K.backend() != backend:
       environ['KERAS_BACKEND'] = backend
       reload(K)
       assert K.backend() == backend

# call the function with "theano"
set_keras_backend("theano")

Type following on command prompt and press enter:

%USERPROFILE%/.keras/keras.json

Change backend in the opened text file and save it. You are done.