无法从keras.utils导入plot_model,遇AttributeError问题求助
问题描述
尝试用plot_model可视化Keras模型时,执行from keras.utils import plot_model抛出AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'dispatch'错误。代码如下:
# %% setup import os import tensorflow as tf tf_model_target_path = os.path.join(os.getcwd(), 'tfModelDir') model = tf.keras.models.load_model(tf_model_target_path) # %% visualize model: save to image file from keras.utils import plot_model plot_model(model, to_file='model.jpg')
环境配置:
- VS Code + Python 3.8.3
- 依赖版本:tensorflow 2.4.1、keras 2.10.0、Keras-Preprocessing 1.1.2、keras-utils 1.0.13
已尝试无效操作:
- 更换导入语句为
from keras.utils.vis_utils import plot_model - 降级tensorflow到2.3.1
原因分析
核心问题是TensorFlow与独立Keras版本不兼容:Keras 2.10.0是独立发行版本,而TensorFlow 2.4.1内置的Keras版本远低于2.10.0,两者混合调用时,独立Keras会尝试调用高版本TF才有的__internal__.dispatch API,低版本TF无法提供该属性,导致报错。Google Colab能正常运行是因为其TF与内置Keras版本完全同步匹配。
解决方案
方案1:使用TensorFlow内置Keras,卸载独立Keras包
TF 2.x版本后官方推荐使用内置的tf.keras,无需安装独立Keras:
- 卸载冲突的独立包:
pip uninstall -y keras keras-utils
- 修改导入语句为TF内置的
plot_model:
# 替换原导入语句 from tensorflow.keras.utils import plot_model
- 重新运行代码,此时会调用TF 2.4.1内置的Keras,避免版本冲突。
方案2:升级TensorFlow到匹配Keras 2.10.0的版本
Keras 2.10.0对应的兼容TF版本为2.10.x(Python 3.8支持该版本):
- 升级TensorFlow:
pip install tensorflow==2.10.0
- 保持原导入语句(或使用
from tensorflow.keras.utils import plot_model),重新运行代码即可。
额外依赖检查
plot_model需要依赖pydot和graphviz生成图像,若未安装需执行:
pip install pydot graphviz
Windows系统需额外安装Graphviz二进制文件,并将其路径添加到系统环境变量PATH中,否则会出现图像生成失败的问题。
内容的提问来源于stack exchange,提问作者crysInCpp
相关产品推荐
相关产品推荐

