TensorFlow导入错误:无法从keras.saving.legacy.serialization导入deserialize_keras_object
问题:TensorFlow 2中创建Keras模型时出现循环导入错误
环境与测试代码
- 运行环境:Visual Studio Code、Python 3.9、已安装TensorFlow 2
- 测试代码:
import tensorflow as tf import numpy as np from tensorflow import keras model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
报错信息
Exception has occurred: ImportError cannot import name 'deserialize_keras_object' from partially initialized module 'keras.saving.legacy.serialization' (most likely due to a circular import) (C:\Users\Erdemdavaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\keras\saving\legacy\serialization.py) File "D:\study\semester 6\Project laborotory(team)\ML_experiment.py", line 4, in <module> model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) ImportError: cannot import name 'deserialize_keras_object' from partially initialized module 'keras.saving.legacy.serialization' (most likely due to a circular import) (C:\Users\Erdemdavaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\keras\saving\legacy\serialization.py)
错误原因
该循环导入错误通常由以下情况导致:
- 版本冲突:TensorFlow 2.x内置了Keras模块,若同时安装了独立的Keras包,两者会产生依赖冲突,触发循环导入。
- 安装损坏:TensorFlow或Keras的安装文件缺失、损坏,导致模块导入逻辑异常。
- 导入方式混用:代码中同时使用
tf.keras和直接导入的keras模块,两者路径不一致,引发内部导入冲突。
解决方法
1. 统一导入方式
修改代码,全程使用TensorFlow官方推荐的tf.keras层级调用,避免混用导入方式:
import tensorflow as tf import numpy as np model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])])
2. 卸载独立Keras包
若单独安装过Keras,执行以下命令移除,确保只使用TensorFlow内置的Keras:
pip uninstall -y keras
3. 重新安装TensorFlow
若安装文件损坏,先卸载现有版本再重新安装适配Python3.9的稳定版(如2.15.0):
pip uninstall -y tensorflow pip install tensorflow==2.15.0
4. 清理Python缓存
删除项目目录及Python site-packages下的__pycache__文件夹,重启VS Code后再运行代码。
内容的提问来源于stack exchange,提问作者Munkhbayar Erdemdavaa
相关产品推荐
相关产品推荐

