提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
LeNet(1998年提出)是卷积网络做识别的开山之作,虽然这篇论文的网络结构现在已经很少使用,但是它对后续卷积网络的发展起到了奠基作用,打下了很好的理论基础.网络一共有5层,卷积1->池化1->卷积2->池化2->全连接,所以被称为LeNet-5。
一、数据获取
import tensorflow as tf
# 数据集
from tensorflow.keras.datasets import mnist
二、 数据加载
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
三、数据处理
# 维度调整
# 卷积神经网络的输入要求是:N H W C,分别是图片数量,图片高度,图片宽度和图片的通道,(灰度图通道为1).
train_images = tf.reshape(train_images,(train_images.shape[0], train_images.shape[1], train_images.shape[2], 1))
print(train_images.shape)
test_images = tf.reshape(test_images,(test_images.shape[0], test_images.shape[1], test_images.shape[2], 1))
print(test_images.shape)
四、模型构建
net = tf.keras.models.Sequential([
# 卷积层: 6个5*5的卷积 sigmoid 大小为5,6个卷积过滤器
tf.keras.layers.Conv2D(filters=6,kernel_size=5,activation='sigmoid',input_shape=(28,28,1)),
# max pooling 大小为2,步长为2
tf.keras.layers.MaxPool2D(pool_size=2, strides=2),
# 卷积层 16 5*5 sigmoid 大小为5,16个卷积过滤器
tf.keras.layers.Conv2D(filters=16, kernel_size=5, activation='sigmoid'),
# max pooling 大小为2,步长为2
tf.keras.layers.MaxPool2D(pool_size=2,strides=2),
# 维度调整 因为输入全连接层的数据为向量
tf.keras.layers.Flatten(),
# 全连接层
tf.keras.layers.Dense(120, activation='sigmoid'),
# 全连接层
tf.keras.layers.Dense(84, activation='sigmoid'),
# 输出层
tf.keras.layers.Dense(10, activation='softmax')
])
net.summary()
# tf.keras.utils.plot_model(net)
五、模型编译
# 设置优化器和损失函数
# 因为之前没有热编码,所以需要使用"sparse_categorical_crossentropy", 使用了热编码后,可以直接使用"categorical_crossentropy"
## 优化器, 损失函数, 评价指标
net.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.9), loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
六、模型训练
# 训练5次,每次128个数据,verbose=1用来显示训练过程
net.fit(train_images, train_labels, epochs=5, batch_size=128, verbose=1)
七、模型评估
net.evaluate(test_images, test_labels, verbose=1)