keras绘制网络结构的代码如下:
from keras.utils.vis_utils import plot_model
...
plot_model(model, to_file="model.png", show_shapes=True, show_layer_names=False, rankdir='TB')
第一次运行这个代码时会报错,这时我们需要两个包pydotplus和grahviz
网上很多教程是安装pydot,这个包在python3.5之后就已经不能使用了,如果继续安装的是pydot,即使将grahviz按如下步骤安装完成了之后,还是会继续爆出OSError: `pydot` failed to call GraphViz.Please install GraphViz错误。
在命令行中输入以下指令即可完成安装。
pip install pydotplus
打开grahviz的官网, 下载graphviz。
下载后安装时按照默认一路next。安装完成后还需要将安装目录下的bin目录放到环境变量中。
将以上两步安装完成后运行附录的程序,会继续报出如下的错误:
此时单独打开图中错误处标记的文件,然后将文件中的pydot都替换成pydotplus,到此大功告成!!
结果如下:
测试代码如下:
import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Convolution2D, MaxPooling2D, Flatten
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1)/255.0
x_test = x_test.reshape(-1, 28, 28, 1)/ 255.0
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
model = Sequential()
model.add(Convolution2D(
input_shape=(28, 28, 1),
filters=32,
kernel_size=5,
strides=1,
padding='same',
activation='relu',
name='conv1'
))
model.add(MaxPooling2D(
pool_size=2,
strides=2,
padding='same',
name='pool1'
))
model.add(Convolution2D(64, 5,strides=1, padding='same', activation='relu', name='conv2'))
model.add(MaxPooling2D(2, 2, 'same', name='pool2'))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
plot_model(model, to_file="model.png", show_shapes=True, show_layer_names=False, rankdir='TB')
plt.figure(1)
img = plt.imread("model.png")
plt.imshow(img)
plt.axis('off')
plt.show()