在IPython Notebook中将Keras后端更改为Theano

3

我按照Keras文档页面的指示更改了keras.json文件。但在我的Ipython笔记本中,它仍然显示我正在使用Tensorflow作为后端。

enter image description here

也许这与Jupyter设置有关系?请帮忙看看。我甚至不知道如何找出问题出在哪里。谢谢!


1
请查看此链接 - Autonomous
感谢@ParagS.Chandakkar。但是这对我不起作用。当我执行keras.backend.backend()时,它仍然显示为tensorflow。也许我可以通过卸载tensorflow来解决这个问题? - user3768495
你尝试过使用 KERAS_BACKEND=theano jupyter notebook --no-browser --ip xxx.xxx.xxx.xxx 吗?然后再运行 keras.backend.set_image_dim_ordering('tf')。 - maz
你试过关掉再打开吗? - Thomas Pinetz
@maz 没有,我应该使用什么IP地址来替换你建议的 xxx.xxx.xxx.xxx? - user3768495
@ThomasPinetz 不,我不认为我做过那个 - 我甚至不知道怎么做... - user3768495
2个回答

5

您可以在笔记本的开头尝试以下操作:

import os
os.environ["KERAS_BACKEND"] = "theano"
import keras; import keras.backend
if keras.backend.backend() != 'theano':
    raise BaseException("This script uses other backend")
else:
    keras.backend.set_image_dim_ordering('th')
    print("Backend ok")

基本上,环境变量KERAS_BACKEND可能会在某个时刻被Jupyter覆盖,因此这是强制在导入keras.backend之前将其设置为某个值的一种方法。


我收到以下错误信息:BaseException:此脚本使用其他后端... - Anshul Singh Suryan

1

Python 2.7中有效的方法 - 动态更改Keras后端

# When I executed the suggestion -- the output I got..
BaseExceptionTraceback (most recent call last)
<ipython-input-7-c4352a2d60e6> in <module>()
      3 import keras; import keras.backend
      4 if keras.backend.backend() != 'theano':
----> 5     raise BaseException("This script uses other backend")
      6 else:
      7     keras.backend.set_image_dim_ordering('th')

BaseException: This script uses other backend

-- 如果我们无法动态更改后端,不确定这如何有帮助。

-- 相反,以下内容对我有帮助: 如何在Keras中切换后端(从TensionFlow到Theano)

iPython代码

from keras import backend; print(backend._BACKEND)
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
print ("Change Keras Backend to Theano")        
set_keras_backend("theano")  
from keras import backend; print(backend._BACKEND)

在 iPython 中的输出
tensorflow
Change Keras Backend to Theano
theano

1
对于Python 3.4及以上版本,请使用import importlib; importlib.reload代替reload - shahar_m

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接