AttributeError:无法导入 keras 和分割模型

Posted

技术标签:

【中文标题】AttributeError:无法导入 keras 和分割模型【英文标题】:AttributeError: could not import keras and segmentation models 【发布时间】:2021-09-13 11:59:22 【问题描述】:

我正在尝试导入分割模型和 keras,但出现属性错误,我使用的是张量流 2.5.0 版

import tensorflow as tf
import segmentation_models as sm
import glob
import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
import keras 

from keras.utils import normalize
from keras.metrics import MeanIoU

属性错误:

AttributeError: module 'keras.utils.generic_utils' has no attribute 'populate_dict_with_module_objects'

我尝试安装 tensorflow 2.1.0 版本以解决其他问题中建议的问题,但问题仍然存在,非常感谢任何建议。

按照 cmets 的建议,我正在更新 pip 列表的输出

点子列表:

pip list
Package                            Version
---------------------------------- -------------------
absl-py                            0.12.0
alabaster                          0.7.12
anaconda-client                    1.8.0
anaconda-navigator                 2.0.3
anaconda-project                   0.10.0
antlr4-python3-runtime             4.8
anyio                              2.2.0
appdirs                            1.4.4
argh                               0.26.2
argon2-cffi                        20.1.0
arrow                              0.13.1
asn1crypto                         1.4.0
astroid                            2.6.0
astropy                            4.2.1
astunparse                         1.6.3
async-generator                    1.10
atomicwrites                       1.4.0
attrs                              21.2.0
autopep8                           1.5.6
Babel                              2.9.1
backcall                           0.2.0
backports.functools-lru-cache      1.6.4
backports.shutil-get-terminal-size 1.0.0
backports.tempfile                 1.0
backports.weakref                  1.0.post1
beautifulsoup4                     4.9.3
binaryornot                        0.4.4
bitarray                           2.1.0
bkcharts                           0.2
black                              21.4b2
bleach                             3.3.0
bokeh                              2.3.2
boto                               2.49.0
Bottleneck                         1.3.2
brotlipy                           0.7.0
cachetools                         4.2.2
certifi                            2021.5.30
cffi                               1.14.5
chardet                            4.0.0
click                              8.0.1
cloudpickle                        1.6.0
clyent                             1.2.2
colorama                           0.4.4
conda                              4.10.1
conda-build                        3.21.4
conda-content-trust                0+unknown
conda-pack                         0.6.0
conda-package-handling             1.7.3
conda-repo-cli                     1.0.4
conda-token                        0.3.0
conda-verify                       3.4.2
contextlib2                        0.6.0.post1
cookiecutter                       1.7.2
cryptography                       3.4.7
cycler                             0.10.0
Cython                             0.29.23
cytoolz                            0.11.0
dask                               2021.6.2
decorator                          4.4.2
defusedxml                         0.7.1
detectron2                         0.4.1
diff-match-patch                   20200713
distributed                        2021.6.2
docutils                           0.17.1
efficientnet                       1.0.0
entrypoints                        0.3
et-xmlfile                         1.1.0
fast-slic                          0.4.0
fastcache                          1.1.0
filelock                           3.0.12
flake8                             3.9.0
Flask                              1.1.2
flatbuffers                        1.12
fsspec                             2021.6.0
future                             0.18.2
fvcore                             0.1.5.post20210609
gast                               0.4.0
gco-wrapper                        3.0.7
gevent                             21.1.2
glob2                              0.7
gmpy2                              2.0.8
google-auth                        1.31.0
google-auth-oauthlib               0.4.4
google-pasta                       0.2.0
greenlet                           1.1.0
grpcio                             1.34.1
h5py                               3.1.0
HeapDict                           1.0.1
html5lib                           1.1
hydra-core                         1.1.0
idna                               2.10
image-classifiers                  1.0.0
imageio                            2.9.0
imagesize                          1.2.0
importlib-metadata                 3.10.0
importlib-resources                5.1.4
ImSegm                             0.1.8
inflection                         0.5.1
iniconfig                          1.1.1
intervaltree                       3.1.0
iopath                             0.1.8
ipykernel                          5.3.4
ipython                            7.22.0
ipython-genutils                   0.2.0
ipywidgets                         7.6.3
isort                              5.9.1
itsdangerous                       2.0.1
jdcal                              1.4.1
jedi                               0.17.2
jeepney                            0.6.0
Jinja2                             2.11.3
jinja2-time                        0.2.0
joblib                             1.0.1
json5                              0.9.6
jsonschema                         3.2.0
jupyter                            1.0.0
jupyter-client                     6.1.12
jupyter-console                    6.4.0
jupyter-core                       4.7.1
jupyter-packaging                  0.7.12
jupyter-server                     1.4.1
jupyterlab                         3.0.14
jupyterlab-pygments                0.1.2
jupyterlab-server                  2.4.0
jupyterlab-widgets                 1.0.0
Keras                              2.3.1
Keras-Applications                 1.0.8
keras-nightly                      2.5.0.dev2021032900
Keras-Preprocessing                1.1.2
keyring                            23.0.1
kiwisolver                         1.3.1
lazy-object-proxy                  1.6.0
libarchive-c                       2.9
llvmlite                           0.36.0
locket                             0.2.1
lxml                               4.6.3
Markdown                           3.3.4
MarkupSafe                         1.1.1
matplotlib                         3.4.2
mccabe                             0.6.1
mistune                            0.8.4
mkl-fft                            1.3.0
mkl-random                         1.2.1
mkl-service                        2.3.0
mock                               4.0.3
more-itertools                     8.8.0
mpmath                             1.2.1
msgpack                            1.0.2
multipledispatch                   0.6.0
mypy-extensions                    0.4.3
navigator-updater                  0.2.1
nbclassic                          0.2.6
nbclient                           0.5.3
nbconvert                          6.1.0
nbformat                           5.1.3
nest-asyncio                       1.5.1
networkx                           2.5.1
nibabel                            3.2.1
nltk                               3.6.2
nose                               1.3.7
notebook                           6.4.0
np-utils                           0.5.12.1
numba                              0.53.1
numexpr                            2.7.3
numpy                              1.19.5
numpydoc                           1.1.0
oauthlib                           3.1.1
olefile                            0.46
omegaconf                          2.1.0
opencv-python                      4.4.0.46
openpyxl                           3.0.7
opt-einsum                         3.3.0
packaging                          20.9
pandas                             1.1.4
pandocfilters                      1.4.3
parso                              0.7.0
partd                              1.2.0
patchify                           0.2.3
path                               16.0.0
pathlib2                           2.3.5
pathspec                           0.8.1
pathtools                          0.1.2
patsy                              0.5.1
pbr                                5.6.0
pep8                               1.7.1
pexpect                            4.8.0
pickleshare                        0.7.5
Pillow                             8.2.0
pip                                21.1.2
pkginfo                            1.7.0
planar                             0.4
pluggy                             0.13.1
ply                                3.11
portalocker                        2.3.0
poyo                               0.5.0
prometheus-client                  0.11.0
prompt-toolkit                     3.0.17
protobuf                           3.17.3
psutil                             5.8.0
ptyprocess                         0.7.0
py                                 1.10.0
pyasn1                             0.4.8
pyasn1-modules                     0.2.8
pycocotools                        2.0.2
pycodestyle                        2.6.0
pycosat                            0.6.3
pycparser                          2.20
pycurl                             7.43.0.6
pydocstyle                         6.1.1
pydot                              1.4.2
pyerfa                             2.0.0
pyflakes                           2.2.0
Pygments                           2.9.0
pylint                             2.8.3
pyls-black                         0.4.6
pyls-spyder                        0.3.2
pyodbc                             4.0.0-unsupported
pyOpenSSL                          20.0.1
pyparsing                          2.4.7
pyrsistent                         0.17.3
PySocks                            1.7.1
pytest                             6.2.4
python-dateutil                    2.8.1
python-jsonrpc-server              0.4.0
python-language-server             0.36.2
python-slugify                     5.0.2
pytz                               2021.1
PyWavelets                         1.1.1
pyxdg                              0.27
PyYAML                             5.4.1
pyzmq                              20.0.0
QDarkStyle                         3.0.2
qstylizer                          0.1.10
QtAwesome                          1.0.2
qtconsole                          5.1.0
QtPy                               1.9.0
regex                              2021.4.4
requests                           2.25.1
requests-oauthlib                  1.3.0
rope                               0.19.0
rsa                                4.7.2
Rtree                              0.9.7
ruamel-yaml-conda                  0.15.100
scikit-image                       0.18.1
scikit-learn                       0.24.2
scipy                              1.5.4
seaborn                            0.11.1
SecretStorage                      3.3.1
segmentation-models                1.0.1
Send2Trash                         1.5.0
setuptools                         57.0.0
simplegeneric                      0.8.1
singledispatch                     0.0.0
sip                                4.19.13
six                                1.15.0
sniffio                            1.2.0
snowballstemmer                    2.1.0
sortedcollections                  2.1.0
sortedcontainers                   2.4.0
soupsieve                          2.2.1
Sphinx                             4.0.2
sphinxcontrib-applehelp            1.0.2
sphinxcontrib-devhelp              1.0.2
sphinxcontrib-htmlhelp             2.0.0
sphinxcontrib-jsmath               1.0.1
sphinxcontrib-qthelp               1.0.3
sphinxcontrib-serializinghtml      1.1.5
sphinxcontrib-websupport           1.2.4
spyder                             5.0.3
spyder-kernels                     2.0.3
SQLAlchemy                         1.4.19
statsmodels                        0.12.2
sympy                              1.8
tables                             3.6.1
tabulate                           0.8.9
tblib                              1.7.0
tensorboard                        2.5.0
tensorboard-data-server            0.6.1
tensorboard-plugin-wit             1.8.0
tensorflow                         2.5.0
tensorflow-estimator               2.5.0
tensorflow-gpu                     2.5.0
termcolor                          1.1.0
terminado                          0.9.4
testpath                           0.5.0
testresources                      2.0.1
text-unidecode                     1.3
textdistance                       4.2.1
threadpoolctl                      2.1.0
three-merge                        0.1.1
tifffile                           2021.6.6
tinycss                            0.4
toml                               0.10.2
toolz                              0.11.1
torch                              1.6.0+cu101
torchvision                        0.7.0+cu101
tornado                            6.1
tqdm                               4.51.0
traitlets                          5.0.5
typed-ast                          1.4.2
typing-extensions                  3.7.4.3
ujson                              4.0.2
unicodecsv                         0.14.1
Unidecode                          1.2.0
urllib3                            1.26.5
watchdog                           1.0.2
wcwidth                            0.2.5
webencodings                       0.5.1
Werkzeug                           2.0.1
wheel                              0.36.2
whichcraft                         0.6.1
widgetsnbextension                 3.5.1
wrapt                              1.12.1
wurlitzer                          2.1.0
xlrd                               2.0.1
XlsxWriter                         1.3.8
xlwt                               1.3.0
xmltodict                          0.12.0
yacs                               0.1.8
yapf                               0.31.0
zict                               2.0.0
zipp                               3.4.1
zope.event                         4.5.0
zope.interface                     5.3.0
Note: you may need to restart the kernel to use updated packages.

【问题讨论】:

您能否显示引发此错误的代码段? @StrangeSorcerer : import segmentation_models as sm 是我发现错误的代码段 您能提供“pip list”的输出吗?以及 tf.__version__ 的输出 您是否尝试过打开另一个脚本并尝试直接使用该属性?类似from keras.utils.generic_utils import populate_dict_with_module_objects。查看问题是在segmentation_models还是keras @StrangeSorcerer ,是的,我做到了,这是输出 ImportError: cannot import name 'populate_dict_with_module_objects' from 'keras.utils.generic_utils' (/home/anaconda3/lib/python3.8/site-packages /keras/utils/generic_utils.py) 【参考方案1】:

我已经通过添加tf.compat.v1.enable_eager_execution() 来解决我的问题,它工作正常

import tensorflow as tf
from tensorflow import keras 
tf.compat.v1.enable_eager_execution()
import segmentation_models as sm
import glob
import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
#import keras 
from tensorflow.keras.utils import normalize
from tensorflow.keras.metrics import MeanIoU

【讨论】:

以上是关于AttributeError:无法导入 keras 和分割模型的主要内容,如果未能解决你的问题,请参考以下文章

为啥keras安装以后导入失败?

AttributeError:模块'keras'没有属性'initializers'

无法导入freegames python包:AttributeError:模块'collections'没有属性'Sequence'

AttributeError:模块'tensorflow'没有带Ke ras的属性'name_scope'

AttributeError:模块 'keras.utils' 没有属性 'Sequence'

从脚本导入已安装的包会引发“AttributeError:模块没有属性”或“ImportError:无法导入名称”