Skip to main content
 首页 » 编程设计

python之keras-mxnet 无法从 pip 中正确拉取

2025年05月04日24虾米哥

导入keras时出错

>>> import keras 
/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/daal/__init__.py:19: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses 
  import imp 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/__init__.py", line 3, in <module> 
    from . import utils 
  File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/utils/__init__.py", line 6, in <module> 
    from . import conv_utils 
  File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/utils/conv_utils.py", line 9, in <module> 
    from .. import backend as K 
  File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/backend/__init__.py", line 98, in <module> 
    raise ValueError('Invalid backend. Missing required entry : ' + e) 
ValueError: Invalid backend. Missing required entry : placeholder 

我正确安装了 mxnet:

>>> import mxnet as mx 
/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/daal/__init__.py:19: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses 
  import imp 
>>> a = mx.nd.ones((2,3)) 
>>> b = a*2+1 
>>> b.asnumpy() 
array([[3., 3., 3.], 
       [3., 3., 3.]], dtype=float32) 

我在 pip 中的 keras

(idp3) ❯ pip freeze | grep keras 
keras-mxnet==2.2.0 

~/.keras/keras.json

(idp3) ❯ cat ~/.keras/keras.json 
{ 
    "floatx": "float32", 
    "epsilon": 1e-07, 
    "backend": "mxnet", 
    "image_data_format": "channels_last" 
} 

看来我的 keras 站 pip 包中的 __init__.py 与当前 github 版本的不一样:

我的 keras/backend/__init__.py
# 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. 
    ... 

但是在keras-mxnet's github rep o:

# 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 * 
elif _BACKEND == 'mxnet': 
    sys.stderr.write('Using MXNet backend\n') 
    from .mxnet_backend import * 
else: 
    # Try and load external backend. 
    ... 

请您参考如下方法:

看起来您混合安装了 Keras 和 Keras-MXNet,这可以解释为什么您的 init.py 不是最新的。

我建议对 keras 和 keras-mxnet 进行 pip 卸载,然后重新安装 keras-mxnet。

如果您确实需要在一台机器上安装两个版本,您可以将它们安装在不同的 conda 环境中。