keras模型可视化pydot-ng 和 graphviz安装问题(ubuntu)

来源:互联网 发布:阿里云服务器的外网ip 编辑:程序博客网 时间:2024/06/06 18:31

方法一:

keras.utils.vis_utils模块提供了画出Keras模型的函数(利用graphviz)
然而模型可视化过程会报错误:

from keras.utils import plot_modelplot_model(model, to_file='model.png')

keras文档给出的解决方法:

pip install pydot-ng & brew install graphviz

安装时会提醒你添加环境变量:

You may want to update following environments after installed linuxbrew.  PATH, MANPATH, INFOPATH 

打开.bashrc:

gedit ~/.bashrc

在最后添加提示的环境变量即可
如果已经安装.linuxbrew ,若提示错误,可以把.linuxbrew删除再继续安装
详细homebrew在Linux下的使用讨论及Linuxbrew安装方法

方法二 :

打开keras可视化代码:

def _check_pydot():    try:        # Attempt to create an image of a blank graph        # to check the pydot/graphviz installation.        pydot.Dot.create(pydot.Dot())    except Exception:        # pydot raises a generic Exception here,        # so no specific class can be caught.        raise ImportError('Failed to import pydot. You must install pydot'                          ' and graphviz for `pydotprint` to work.')

可自行pip安装:

sudo apt-get install graphvizsudo pip install pydot-ng

注意需要先安装graphviz再装pydot-ng

可视化结果

随便写了一个2层LSTM的网络:

from keras.models import Modelfrom keras.layers import LSTM, Activation, Inputimport numpy as npfrom keras.utils.vis_utils import plot_modeldata_dim = 1timesteps = 12num_classes = 4inputs = Input(shape=(12,1))lstm1 = LSTM(32, return_sequences=True)(inputs)lstm2 = LSTM(4 , return_sequences=True)(lstm1)outputs = Activation('softmax')(lstm2)model = Model(inputs=inputs,outputs=outputs)model.compile(loss='categorical_crossentropy',              optimizer='rmsprop',              metrics=['accuracy'])x_train = np.random.random((1000, timesteps, data_dim))y_train = np.random.random((1000, timesteps, num_classes))x_val = np.random.random((100, timesteps, data_dim))y_val = np.random.random((100, timesteps, num_classes))model.fit(x_train, y_train,          batch_size=64, epochs=5,          validation_data=(x_val, y_val))#模型可视化plot_model(model, to_file='model.png')x = np.arange(12).reshape(1,12,1)a = model.predict(x,batch_size=64)print a

结果:
LSTM模型可视化