CNN构建网络
代码:
import tensorflow as tf
from tensorflow import keras
import numpy as np
model=keras.Sequential() # 创建网络序列
添加第一层卷积层和池化层
model.add(keras.layers.Conv2D(filters=32,kernel_size = 5,strides = (1,1),
padding = 'same',activation = tf.nn.relu,input_shape = (28,28,1)))
model.add(keras.layers.MaxPool2D(pool_size=(2,2), strides = (2,2), padding = 'valid'))
添加第二层卷积层和池化层
model.add(keras.layers.Conv2D(filters=64,kernel_size = 3,strides = (1,1),padding = 'same',activation = tf.nn.relu))
model.add(keras.layers.MaxPool2D(pool_size=(2,2), strides = (2,2), padding = 'valid'))
添加dropout层 以减少过拟合
model.add(keras.layers.Dropout(0.25))
model.add(keras.layers.Flatten())
添加两层全连接层
model.add(keras.layers.Dense(units=128,activation = tf.nn.relu))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Dense(units=10,activation = tf.nn.softmax))
以上网络中,我们利用keras.layers添加了两个卷积池化层,之后又添加了dropout层,防止过拟合,最后添加了两层全连接层。