无法从 'tensorflow.compat.v2.experimental' 导入名称 'dtensor'

Cannot import name 'dtensor' from 'tensorflow.compat.v2.experimental'

我是一个学校项目的 TensorFlow 新手,尽管在我的 Windows 10 机器上尝试 运行 TensorFlow 时遇到问题。代码 运行 在我的 MacOS 机器上没问题。 非常感谢任何帮助

Traceback (most recent call last):
  File "c:\Users\Fynn\Documents\GitHub\AlpacaTradingBot\ai.py", line 15, in <module>
    from keras.models import Sequential, load_model
  File "C:\Users\Fynn\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\__init__.py", line 24, in <module>
    from keras import models
  File "C:\Users\Fynn\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\models\__init__.py", line 18, in <module>
    from keras.engine.functional import Functional
  File "C:\Users\Fynn\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\functional.py", line 24, in <module>
    from keras.dtensor import layout_map as layout_map_lib
  File "C:\Users\Fynn\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\dtensor\__init__.py", line 22, in <module>
    from tensorflow.compat.v2.experimental import dtensor as dtensor_api  # pylint: disable=g-import-not-at-top
ImportError: cannot import name 'dtensor' from 'tensorflow.compat.v2.experimental' (C:\Users\Fynn\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\_api\v2\compat\v2\experimental\__init__.py)

这可能是由于您的 tensorflowkeras 版本不兼容造成的。特别是我在 tensorflow==2.6.0keras==2.9.0 中看到了这一点,但如果其他版本也会导致这种情况,我也不会感到惊讶。

通过以下方式更新您的 tensorflow 版本:

pip install tensorflow==2.8

或通过以下方式降级您的 keras 版本:

pip install keras==2.6

我尝试了很多解决方案都无济于事,最后这个对我有用!

pip3 uninstall tensorflow absl-py astunparse flatbuffers gast google-pasta grpcio h5py keras keras-preprocessing libclang numpy opt-einsum protobuf setuptools six tensorboard tensorflow-io-gcs-filesystem termcolor tf-estimator-nightly typing-extensions wrapt
pip3 install --disable-pip-version-check --no-cache-dir tensorflow

希望对您有所帮助!!!

在您必须删除位于 site-package 的 tensorflow 和 keras 文件夹之前。 打开管理员命令提示符使用此代码

pip uninstall tensorflow 

pip install tensorflow --ignore-installed