How can I change the backend of Keras dynamically?

半腔热情 提交于 2021-01-29 05:01:09

问题


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.

来源:https://stackoverflow.com/questions/62735466/how-can-i-change-the-backend-of-keras-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!