在Jupyter Notebook中使用plot_model可视化TensorFlow模型遇安装问题
TensorFlow plot_model 已安装依赖仍报错的解决方法
问题描述
我按照plot_model官方文档的示例代码,在Jupyter Notebook中尝试可视化TensorFlow模型:
input = tf.keras.Input(shape=(100,), dtype='int32', name='input') x = tf.keras.layers.Embedding( output_dim=512, input_dim=10000, input_length=100)(input) x = tf.keras.layers.LSTM(32)(x) x = tf.keras.layers.Dense(64, activation='relu')(x) x = tf.keras.layers.Dense(64, activation='relu')(x) x = tf.keras.layers.Dense(64, activation='relu')(x) output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(x) model = tf.keras.Model(inputs=[input], outputs=[output]) dot_img_file = '/tmp/model_1.png' tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)
但系统返回错误提示:
You must install pydot (
pip install pydot) and install graphviz (see instructions at https://graphviz.gitlab.io/download/) for plot_model to work.
我已通过pip install安装并验证了以下Python库:
- Name: pydot,Version: 1.2.3
- Name: graphviz,Version: 0.20.1
- Name: pydotplus,Version: 2.0.2
且能在Notebook中正常导入这些包,但仍出现相同报错。
解决步骤
安装系统级Graphviz程序
Python的graphviz包只是Graphviz系统程序的接口,必须安装底层的Graphviz系统软件:- Windows:下载对应版本安装包,安装时勾选"Add Graphviz to system PATH"选项
- macOS:执行
brew install graphviz - Debian/Ubuntu:执行
sudo apt-get install graphviz - CentOS/RHEL:执行
sudo yum install graphviz
重启Jupyter Notebook
安装完成后,必须重启Jupyter内核或整个Notebook服务,确保环境变量生效。验证Graphviz可用性
在终端或Jupyter代码单元格中执行以下命令,检查是否能正常调用:dot -V返回Graphviz版本信息则说明安装成功。
指定pydotplus作为后端(可选)
如果仍有问题,可手动指定使用pydotplus处理:import pydotplus tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True, pydot=pydotplus)
内容的提问来源于stack exchange,提问作者momo33
相关产品推荐
相关产品推荐

