tf环境下,VGG16训练mnist ,并达到一个很高的准确率,给出完整代码,打印运算结果,打印运行时间 并可视化
时间: 2024-05-13 12:15:32 浏览: 61
VGG16实现MNIST数据集识别任务.py
首先需要导入相关的库:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
import time
```
接下来加载MNIST数据集并进行预处理:
```python
# 加载数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 将数据转换为float32类型
train_images = train_images.astype('float32')
test_images = test_images.astype('float32')
# 将像素值缩放到0-1之间
train_images /= 255
test_images /= 255
# 将标签转换为one-hot编码
train_labels = to_categorical(train_labels, num_classes=10)
test_labels = to_categorical(test_labels, num_classes=10)
```
然后构建VGG16模型:
```python
model = Sequential()
# Block 1
model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
# Block 2
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
# Block 3
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
# Block 4
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
# Block 5
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
# 全连接层
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dense(4096, activation='relu'))
model.add(Dense(10, activation='softmax'))
# 打印模型结构
model.summary()
```
接着进行模型训练:
```python
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 记录开始时间
start_time = time.time()
# 训练模型
model.fit(train_images.reshape(-1, 28, 28, 1), train_labels, epochs=5, batch_size=64,
validation_data=(test_images.reshape(-1, 28, 28, 1), test_labels))
# 记录结束时间
end_time = time.time()
# 打印运行时间
print("运行时间:%.2f秒" % (end_time - start_time))
```
最后进行模型评估和可视化:
```python
# 评估模型
test_loss, test_acc = model.evaluate(test_images.reshape(-1, 28, 28, 1), test_labels)
print('测试集准确率:%.2f%%' % (test_acc * 100))
# 可视化
predictions = model.predict(test_images.reshape(-1, 28, 28, 1))
fig, axes = plt.subplots(10, 10, figsize=(15, 15))
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
ax.imshow(test_images[i], cmap='binary')
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel(np.argmax(predictions[i]))
plt.show()
```
阅读全文