天天看点

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:

在最后添加提示的环境变量即可

如果已经安装

.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 = 
timesteps = 
num_classes = 

inputs = Input(shape=(,))
lstm1 = LSTM(, return_sequences=True)(inputs)
lstm2 = LSTM( , 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((, timesteps, data_dim))
y_train = np.random.random((, timesteps, num_classes))

x_val = np.random.random((, timesteps, data_dim))
y_val = np.random.random((, timesteps, num_classes))

model.fit(x_train, y_train,
          batch_size=, epochs=,
          validation_data=(x_val, y_val))
#模型可视化
plot_model(model, to_file='model.png')
x = np.arange().reshape(,,)
a = model.predict(x,batch_size=)
print a
           

结果:

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

继续阅读