Python实现LeNet()网络模型对MNIST数据集进行分类
发布时间:2023-12-24 16:27:37
LeNet是一个经典的卷积神经网络模型,最早由Yann LeCun在1998年提出,用于手写数字识别。它是 个在实际问题上成功应用的卷积神经网络模型,也被用于MNIST数据集的分类任务。
LeNet网络模型主要由卷积层、池化层、全连接层和输出层组成。下面是一个基本的LeNet网络结构:
Convolution (5x5, 6 filters) -> ReLU -> MaxPooling (2x2) -> Convolution (5x5, 16 filters) -> ReLU -> MaxPooling (2x2) -> Flattening -> Fully Connected (120 neurons) -> ReLU -> Fully Connected (84 neurons) -> ReLU -> Fully Connected (10 neurons) -> Softmax
下面是一个使用Python实现LeNet网络模型对MNIST数据集进行分类的示例代码:
import tensorflow as tf
from tensorflow.keras import layers
# 加载MNIST数据集
mnist = tf.keras.datasets.mnist
(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 = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 构建LeNet网络模型
model = tf.keras.Sequential()
model.add(layers.Conv2D(filters=6, kernel_size=(5, 5), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Conv2D(filters=16, kernel_size=(5, 5), activation='relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(units=120, activation='relu'))
model.add(layers.Dense(units=84, activation='relu'))
model.add(layers.Dense(units=10, activation='softmax'))
# 编译和训练模型
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1)
# 评估模型
score = model.evaluate(x_test, y_test)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
这段代码首先加载MNIST数据集,并进行了数据预处理。接下来构建LeNet网络模型,使用了Sequential模型和Layers模块。然后编译模型,设定了优化器、损失函数和评估指标。最后通过fit()函数来训练模型,并使用evaluate()函数对测试集进行评估。
LeNet网络模型是一个经典的卷积神经网络模型,在MNIST数据集上取得了较好的分类效果。通过使用Python实现LeNet网络模型,我们可以对MNIST数据集进行准确的手写数字识别。
