如何在不同的conda环境下设置不同的keras后端

2024-09-28 04:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在不同的conda环境中设置不同的keras后端?因为在特定的环境中,如果我在keras.json中将后端更改为tensorflow,那么在另一个python环境中,keras后端也将是tensorflow。我的文档中只有一个keras.json。在


Tags: 文档json环境tensorflowconda中将keras
3条回答

以下是我为自己的目的所做的,逻辑与Kedaranswer相同,但在Windows安装(和Keras版本)上,其位置和文件名可能有所不同:

1/设置a特定keras.json文件文件,在目标Python环境的文件夹中。修改“backend”值。在

2/然后强制加载_后端.py'(一个特定于您的Python环境)来加载这个特定的keras.json文件. 另外,强制de“default backend”到您想要的同一个文件中。在

==========================================================

详细信息

1.1打开需要特定后端的Anaconda环境文件夹。在我的例子中是C:\ProgramData\Anaconda3\envs\[MyAnacondaEnvironment]\

1.2在这里创建一个文件夹.keras,并在该文件夹中复制或创建一个文件keras.json文件(我是从C:\Users\[MyWindowsUserProfile]\.keras复制的\keras.json文件). 在

现在在这个文件中,改变你想要的后端,我已经选择了'cntk'进行一些测试。文件内容现在应该如下所示:

{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "cntk",
    "image_data_format": "channels_last"
}

文件名和位置类似于C:\ProgramData\Anaconda3\envs\[MyAnacondaEnvironment]\.keras\keras.json文件在

2.1现在打开“加载”文件_后端.py'特定于您正在定制的环境,位于(在我的例子中)C:\ProgramData\Anaconda3\envs\[MyAnacondaEnvironment]\Lib\site packages\keras\backend

2.2在我的Keras版本(2.3.1)中,这里的第17行到第25行,该文件通常在环境变量或当前Windows用户的帮助下,从它所在的配置文件加载后端。这就是为什么目前您的后端是跨环境的。在

通过强制加载来消除这个问题_后端.py'查看要直接加载到特定于环境的配置文件(步骤1.2中创建的配置文件)中的后端

例如,第26行_后端.py'文件(在我的例子中是第26行,在尝试自动加载配置文件之后)添加该行(并为您自己的位置自定义):

_keras_dir='C:\ProgramData\Anaconda3\envs\[MyAnacondaEnvironment]\.keras'##强制脚本从特定文件获取配置

3.1然后替换(在我的例子中是第28行,在您强制使用_keras_dir path之后)默认的后端_backend='tensorflow'替换为_backend='cntk'。在

你应该完蛋了

一种解决方案是为不同的环境创建不同的用户,并为这两种环境放置不同的^{}文件:

$HOME/.keras/keras.json

这样您就可以独立地更改任何keras参数。在


如果只需要更改后端,那么使用KERAS_BACKENDenv变量会更容易。以下命令将使用tensorflow,而不管keras.json中是什么:

^{pr2}$

所以你可以启动一个新的shell终端,在其中运行export KERAS_BACKEND=tensorflow,所有后续命令都将使用tensorflow。您可以按照this question(如果您永久需要它)中所述,进一步设置每个conda env activation变量:

$PREFIX/etc/conda/activate.d

在水蟒的不同环境中使用不同的keras后端-“env1”和“env2”

  • 激活第一个环境“env1”
  • 使用默认后端从python导入keras(例如,如果无法加载tensorflow,请在该环境中安装tensorflow)
  • 在~文件夹中,将创建一个“.keras”文件夹,其中包含keras.json文件文件
  • 对于其他环境,请将“.keras”文件夹的副本创建为“.keras1”
  • 改变keras.json文件根据要求在该文件夹中的文件(“后端”字段)
  • 要在“env2”中使用该配置,请转到'~/anaconda3/envs/env2/lib/pythonx.x/site packages/keras/backend',然后编辑\uuinit_uu.py文件
  • 进行标记为的更改
  • 您将能够在env1和env2中导入具有不同后端的keras

from __future__ import absolute_import from __future__ import print_function import os import json import sys import importlib from .common import epsilon from .common import floatx from .common import set_epsilon from .common import set_floatx from .common import cast_to_floatx from .common import image_data_format from .common import set_image_data_format # Set Keras base dir path given KERAS_HOME env variable, if applicable. # Otherwise either ~/.keras or /tmp. if 'KERAS_HOME' in os.environ: _keras_dir = os.environ.get('KERAS_HOME') else: _keras_base_dir = os.path.expanduser('~') if not os.access(_keras_base_dir, os.W_OK): _keras_base_dir = '/tmp' _keras_dir = os.path.join(_keras_base_dir, '.keras1')## # Default backend: TensorFlow. _BACKEND = 'tensorflow' # Attempt to read Keras config file. _config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json')) if os.path.exists(_config_path): try: with open(_config_path) as f: _config = json.load(f) except ValueError: _config = {} _floatx = _config.get('floatx', floatx()) assert _floatx in {'float16', 'float32', 'float64'} _epsilon = _config.get('epsilon', epsilon()) assert isinstance(_epsilon, float) _backend = _config.get('backend', _BACKEND) _image_data_format = _config.get('image_data_format', image_data_format()) assert _image_data_format in {'channels_last', 'channels_first'} set_floatx(_floatx) set_epsilon(_epsilon) set_image_data_format(_image_data_format) _BACKEND = _backend # Save config file, if possible. if not os.path.exists(_keras_dir): try: os.makedirs(_keras_dir) except OSError: # Except permission denied and potential race conditions # in multi-threaded environments. pass if not os.path.exists(_config_path): _config = { 'floatx': floatx(), 'epsilon': epsilon(), 'backend': _BACKEND, 'image_data_format': image_data_format() } try: with open(_config_path, 'w') as f: f.write(json.dumps(_config, indent=4)) except IOError: # Except permission denied. pass # Set backend based on KERAS_BACKEND flag, if applicable. if 'KERAS_BACKEND' in os.environ: _backend = os.environ['KERAS_BACKEND'] _BACKEND = _backend # Import backend functions. if _BACKEND == 'cntk': sys.stderr.write('Using CNTK backend\n') from .cntk_backend import * elif _BACKEND == 'theano': sys.stderr.write('Using Theano backend.\n') from .theano_backend import * elif _BACKEND == 'tensorflow': sys.stderr.write('Using TensorFlow backend.\n') from .tensorflow_backend import * else: # Try and load external backend. try: backend_module = importlib.import_module(_BACKEND) entries = backend_module.__dict__ # Check if valid backend. # Module is a valid backend if it has the required entries. required_entries = ['placeholder', 'variable', 'function'] for e in required_entries: if e not in entries: raise ValueError('Invalid backend. Missing required entry : ' + e) namespace = globals() for k, v in entries.items(): # Make sure we don't override any entries from common, such as epsilon. if k not in namespace: namespace[k] = v sys.stderr.write('Using ' + _BACKEND + ' backend.\n') except ImportError: raise ValueError('Unable to import backend : ' + str(_BACKEND)) def backend(): """Publicly accessible method for determining the current backend. # Returns String, the name of the backend Keras is currently using. # Example ```python >>> keras.backend.backend() 'tensorflow' ``` """ return _BACKEND

和13;
和13;

相关问题 更多 >

    热门问题