0

Preliminary information: The answers given for the previously asked related questions (e.g., How to change the backend of Keras to Theano?, How to switch Backend with Keras (from TensorFlow to Theano)) did not work for me. Hence, I've created my own question.

As the title clearly describes, I need to change the backend of Keras dynamically (per run). How can I do this? I'm using Python 3.

Here is a function that I've created through the feedback on the web:

from keras import backend as K
from importlib import reload


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

When I call the function above such as set_keras_backend('theano'), getting an assertion error as follows:

AssertionError: assert K.backend() == backend

p.s. (1) I'm using macOS Catalina 10.15.5.

(2) The versions of TensorFlow, and Keras are 2.2.0, and 2.4.3, respectively, which are the most recent stable versions.

(3) The package for the Theano, namely Theano, was already installed through the pip.

talha06
  • 6,206
  • 21
  • 92
  • 147
  • Keras version 2.3.0-tf indicates it is actually tf.keras, not keras, are you sure your code is using that version? – Dr. Snoopy Jul 05 '20 at 00:31
  • Yes, these were taken from the console output. First, I've installed the `tensorflow` package, then I've installed the `keras` package through the `pip`. Anything wrong here? @Dr.Snoopy – talha06 Jul 05 '20 at 01:38
  • How did you print the keras version? – Dr. Snoopy Jul 05 '20 at 01:41
  • Here it is: @Dr.Snoopy `import tensorflow.keras as keras print(f'Keras version: {keras.__version__}')` – talha06 Jul 05 '20 at 01:47
  • If I use Keras directly, getting the Keras version as `2.4.3`. @Dr.Snoopy – talha06 Jul 05 '20 at 01:49
  • 1
    That is exactly what I am talking about, you are printing the version of tf.keras. Keras and tf.keras are not the same library, tf.keras only supports TensorFlow as the backend. – Dr. Snoopy Jul 05 '20 at 01:49
  • Thanks for that, but the error still happens (I've changed the import of Keras). @Dr.Snoopy – talha06 Jul 05 '20 at 01:51

0 Answers0