[英]Remember a different set of files in Spyder with different conda environments
[英]How to set different keras backend in different conda environments
如何在不同的conda
環境中設置不同的 keras 后端? 因為在特定的環境中,如果我改變后端tensorflow
在keras.json
,然后在另一個Python環境,keras后端會tensorflow
了。 我的文檔中只有一個keras.json
。
用於在 Anaconda 的不同環境中使用不同的 keras 后端 - 'env1' 和 'env2'
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
這是我為自己的目的所做的,與Kedar的答案相同的邏輯,但在 Windows 安裝(和 Keras 版本)上,位置和文件名可能不同:
1/在目標 Anaconda 環境的文件夾中設置特定的 keras.json文件。 修改“后端”值。
2/然后強制'load_backend.py' (特定於你的anaconda env的那個)加載這個特定的keras.json。 此外,在同一個文件中強制將“默認后端”設置為您想要的后端。
================================================== ======
詳情:
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現在打開特定於您正在自定義的環境的文件“load_backend.py”,位於此處(在我的情況下)C:\\ProgramData\\Anaconda3\\envs\\[MyAnacondaEnvironment]\\Lib\\site-packages\\keras\\backend
2.2在我的 Keras 版本 (2.3.1) 中的第 17 到 25 行,該文件通常從它在環境變量或當前 Windows 用戶的幫助下定位的配置文件加載后端。 這就是為什么目前您的后端是跨環境的。
通過強制“load_backend.py”查看直接在您的環境特定配置文件(您在步驟 1.2 中創建的配置文件)中加載哪個后端來擺脫這種情況
例如,'load_backend.py' 文件的第 26 行(在我的例子中是第 26 行,無論如何在嘗試自動加載配置文件之后)添加該行(並為您自己的位置自定義它):
_keras_dir = 'C:\\ProgramData\\Anaconda3\\envs\\[MyAnacondaEnvironment]\\.keras' ##強制腳本從特定文件獲取配置
3.1然后用 _BACKEND = 'cntk' 替換(在我的例子中是第 28 行,無論如何在你強制 _keras_dir 路徑之后)默認后端 _BACKEND = 'tensorflow'。
你應該完成
一種解決方案是為不同的環境創建不同的用戶,並為兩者放置不同的keras.json
文件:
$HOME/.keras/keras.json
這樣您就可以獨立更改任何 keras 參數。
如果您只需要更改后端,使用KERAS_BACKEND
變量會更容易。 以下命令將使用tensorflow
,無論keras.json
是什么:
$ KERAS_BACKEND=tensorflow python -c "from keras import backend"
Using TensorFlow backend.
因此,您可以啟動一個新的 shell 終端,在其中運行export KERAS_BACKEND=tensorflow
並且所有后續命令都將使用tensorflow
。 您可以進一步設置每個 conda env 激活的變量,如本問題中所述(如果您永久需要它):
$PREFIX/etc/conda/activate.d
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.