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

方法一:

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

from keras.utils import plot_model
plot_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 graphviz
sudo pip install pydot-ng

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

可视化结果

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

from keras.models import Model
from keras.layers import LSTM, Activation, Input
import numpy as np
from keras.utils.vis_utils import plot_model

data_dim = 1
timesteps = 12
num_classes = 4

inputs = 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模型可视化

猜你喜欢

转载自blog.csdn.net/qq_34564612/article/details/78851001