用tensorflow2.0使用卷积训练MNIST数据集包含验证集,并打印训练误差,和准确率
时间: 2024-05-03 20:22:10 浏览: 185
以下是使用tensorflow2.0训练MNIST数据集的代码:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
# 加载MNIST数据集
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# 将像素值缩放到0到1之间
train_images, test_images = train_images / 255.0, test_images / 255.0
# 构建模型
model = models.Sequential([
layers.Reshape((28, 28, 1), input_shape=(28, 28)),
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))
# 打印训练误差和准确率
print("训练误差:", history.history['loss'])
print("训练准确率:", history.history['accuracy'])
print("验证误差:", history.history['val_loss'])
print("验证准确率:", history.history['val_accuracy'])
```
在这个例子中,我们使用了卷积神经网络来训练MNIST数据集,并使用了验证集来评估模型的性能。训练过程中,我们记录了训练误差和准确率以及验证误差和准确率,并在训练完成后打印了这些值。
阅读全文