keras 12_繪制網絡結構
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,MaxPool2D,Flatten
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config = config)
# 載入資料
(x_train,y_train),(x_test,y_test) = mnist.load_data()
print("x_train.shape:",x_train.shape,"y_train.shape:",y_train.shape)
# 将資料轉由(60000,28,28)轉換為(60000,784)的格式
# x_train=x_train.reshape(x_train.shape[0],-1)/255.0
# x_test=x_test.reshape(x_test.shape[0],-1)/255.0
x_train=x_train.reshape(-1,28,28,1)/255.0
x_test=x_test.reshape(-1,28,28,1)/255.0
# 将資料格式轉換為one-hot編碼的格式
y_train=np_utils.to_categorical(y_train,num_classes=10)
y_test=np_utils.to_categorical(y_test,num_classes=10)
# 定義轉換模型
model = Sequential()
# 第一個卷積層
# input_shape:輸入平面
# filter:卷積核、濾波器個數
# kernel_size:卷積視窗大小
# strides:步長
# padding: padding方式,same/valid
# activation:激活函數
model.add(Convolution2D(
input_shape=(28,28,1),
filters=32,
kernel_size=5,
strides=1,
padding="same",
activation="relu",
name="conv1"
))
# 第一個池化層
model.add(MaxPool2D(
pool_size=2,
strides=2,
padding="same",
name="poll1"
))
# 第二個卷積層
model.add(Convolution2D(
filters=64,
kernel_size=5,
strides=1,
padding="same",
activation="relu",
name="conv2"
))
# 第二個池化層
model.add(MaxPool2D(
pool_size=2,
strides=2,
padding="same",
name="poll2"
))
# 将第二個池化層的輸出扁平化1維
model.add(Flatten())
# 第一個全連接配接層
model.add(Dense(1024,activation="relu"))
# Dropout
model.add(Dropout(0.5))
#第二個全連接配接層
model.add(Dense(10,activation="softmax"))
# 定義優化器
adam = Adam(lr=0.001)
# 定義優化器
model.compile(optimizer=adam,loss="categorical_crossentropy",metrics=["accuracy"])
# 訓練模型
model.fit(x_train,y_train,batch_size=32,epochs=1)
# 模型評估
loss,accuracy = model.evaluate(x_test, y_test)
print("test loss:",loss)
print("test accuracy:",accuracy)
# 列印網絡結構
# plot_model(model,to_file="model.png",show_shapes=True,show_layer_names="False",rankdir="TB")
plot_model(model,to_file="model.png",show_shapes=True,show_layer_names="False",rankdir="TB")
plt.figure(figsize=(10,10))
plt.imread("model.png")
plt.axis("off")
plt.show()