You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab中Graphviz失效,调用plot_model报AttributeError求助

解决plot_model()报错AttributeError: 'Model' object has no attribute '_container_nodes'

刚碰到过一模一样的问题!这个错误确实是新版Keras(3.x之后独立出来的版本)的API变化导致的,再加上Google Colab里Graphviz的环境配置有额外坑,咱们一步步解决:

1. 先理清楚Keras版本与导入方式的问题

这个报错最常见的原因是混用了独立Keras和TensorFlow内置的tf.keras:

  • 如果你的my_resnet是用tf.keras构建的(比如从tensorflow.keras.applications导入的ResNet),那你必须用TensorFlow自带的plot_model工具,而不是独立Keras的:
    # 替换原来的导入语句
    from tensorflow.keras.utils import plot_model
    # 可以加上show_shapes等参数让图更清晰
    plot_model(my_resnet, to_file='model.png', show_shapes=True, show_layer_names=True)
    
  • 如果确实要使用独立Keras的plot_model,要么确保你的模型是用纯Keras(而非tf.keras)构建的,要么临时降级Keras到2.x版本(不推荐长期用,除非有特殊需求):
    pip install keras==2.15.0
    

2. 修复Google Colab里的Graphviz环境

Colab里光用pip装pydot和graphviz是不够的,得先装系统级依赖,按顺序运行这些命令:

!apt-get install -y graphviz libgraphviz-dev
!pip install pydotplus pydot

运行完后一定要重启Colab的运行时(点顶部菜单栏的Runtime -> Restart runtime),不然环境不会生效。

另外,Colab里可以直接显示生成的模型图,不用自己找文件,调试更方便:

from tensorflow.keras.utils import plot_model
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 生成模型图
plot_model(my_resnet, to_file='model.png', show_shapes=True)
# 读取并显示
img = mpimg.imread('model.png')
plt.figure(figsize=(20,10))
plt.imshow(img)
plt.axis('off')
plt.show()

3. 临时替代方案:用summary()快速查看架构

如果plot_model还是折腾不好,可以先用model.summary()应急,虽然不是可视化图,但能清晰看到每层的输出形状、参数数量,足够快速排查模型结构问题:

my_resnet.summary()

要是你用的是纯Keras 3.x的模型,还可以试试给plot_model加expand_nested=True参数,有时候能避开容器节点找不到的问题:

from keras.utils import plot_model
plot_model(my_resnet, to_file='model.png', expand_nested=True)

内容的提问来源于stack exchange,提问作者Lasani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:12