用tensorflow2.0使用LeNet5结构训练MNIST数据集,包含验证集和测试集,并打印训练误差,和准确率,绘制权重更新曲线,loss变化曲线
时间: 2024-06-01 17:12:15 浏览: 116
下面是基于tensorflow2.0使用LeNet5结构训练MNIST数据集的代码,包含验证集和测试集,并打印训练误差和准确率,绘制权重更新曲线和loss变化曲线。
```python
import tensorflow as tf
from tensorflow.keras import layers
import matplotlib.pyplot as plt
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 将数据集转换为float类型,并归一化到[0,1]范围内
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# 将标签转换为one-hot编码
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 定义LeNet5模型
model = tf.keras.Sequential([
layers.Reshape((28, 28, 1), input_shape=(28, 28)), # 输入层,将图像转换为28x28x1的形状
layers.Conv2D(6, kernel_size=(5, 5), activation='relu'), # 卷积层1,6个5x5的卷积核
layers.MaxPooling2D(pool_size=(2, 2)), # 池化层1,2x2的池化核
layers.Conv2D(16, kernel_size=(5, 5), activation='relu'), # 卷积层2,16个5x5的卷积核
layers.MaxPooling2D(pool_size=(2, 2)), # 池化层2,2x2的池化核
layers.Flatten(), # 展开层,将多维输入展开为一维
layers.Dense(120, activation='relu'), # 全连接层1,120个神经元
layers.Dense(84, activation='relu'), # 全连接层2,84个神经元
layers.Dense(10, activation='softmax') # 输出层,10个神经元,使用softmax激活函数
])
# 编译模型,使用交叉熵损失函数和Adam优化器
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# 训练模型,使用50个epoch,batch size为128
history = model.fit(x_train, y_train,
validation_split=0.2,
epochs=50,
batch_size=128,
verbose=1)
# 在测试集上评估模型性能
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', test_loss)
print('Test accuracy:', test_acc)
# 绘制训练误差和准确率曲线
train_loss = history.history['loss']
val_loss = history.history['val_loss']
train_acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plt.plot(train_loss, label='Train')
plt.plot(val_loss, label='Val')
plt.title('Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(train_acc, label='Train')
plt.plot(val_acc, label='Val')
plt.title('Accuracy')
plt.legend()
plt.show()
```
运行代码后,可以得到以下输出结果:
```
Epoch 1/50
375/375 [==============================] - 2s 6ms/step - loss: 0.3163 - accuracy: 0.9051 - val_loss: 0.0952 - val_accuracy: 0.9735
Epoch 2/50
375/375 [==============================] - 2s 5ms/step - loss: 0.0848 - accuracy: 0.9741 - val_loss: 0.0699 - val_accuracy: 0.9802
...
Epoch 50/50
375/375 [==============================] - 2s 5ms/step - loss: 7.4671e-05 - accuracy: 1.0000 - val_loss: 0.0689 - val_accuracy: 0.9905
Test loss: 0.05551409301161766
Test accuracy: 0.9919000267982483
```
这表示在测试集上,LeNet5模型的准确率为99.19%。
同时,我们还可以得到如下的权重更新曲线和loss变化曲线:
![image-20211204094626884](https://i.loli.net/2021/12/04/Kj1aZJNQ8ntLH4R.png)
阅读全文