Press "Enter" to skip to content

## 数据准备

```import os
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
import datetime
import tensorflow as tf
import matplotlib.pyplot as plt```

## 加载数据

```# 加载数据
mnist = tf.keras.datasets.mnist
(train_image,train_label),(test_image,test_label) = mnist.load_data()```

## 查看数据信息

```# 查看信息
x_train = train_image
x_test = test_image
y_test = test_label
print(train_image.shape)
print(train_label.shape)
print(test_image.shape)
print(test_label.shape)```

## 查看一张图片

```plt.axis('off')
plt.imshow(train_image[100],cmap='gray')
plt.show()
print(train_label[100])```

## 数据预处理

```# 转换数据格式
# 将28*28的图像转成32*32
x_train = np.pad(x_train, ((0,0), (2,2), (2,2)), 'constant', constant_values=0)
x_test = np.pad(x_test, ((0,0), (2,2), (2,2)), 'constant', constant_values=0)
# 数据类型转化成tf需要的
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# 数据正则化，映射到(0,1)
x_train /= 255
x_test /= 255
# 数据维度转换，四维
x_train = x_train.reshape(x_train.shape[0], 32, 32, 1)
x_test = x_test.reshape(x_test.shape[0], 32, 32, 1)```

## 搭建网络模型

x_trian:训练集
y_trian:训练集标签
batch_size:批大小
num_epochs:训练次数
filters:卷积核个数
kernel_size:卷积核大小
padding:填充方式
activation：激活函数
input_shape:输入数据格式
pool_size：池化大小
strides:步长
units：输出的维数

```# 搭建网络模型
#超参数设置
num_epochs = 5   # 训练次数
batch_size = 64  # 批大小
learning_rate = 0.001  #学习率
model = tf.keras.models.Sequential([
# 第一层卷积层
tf.keras.layers.Conv2D(filters=6, kernel_size=(5,5), padding='valid', activation=tf.nn.relu, input_shape=(32,32,1)),
# 第一池化层
tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=(2,2), padding='same'),
# 第二卷积层
tf.keras.layers.Conv2D(filters=16, kernel_size=(5,5), padding='valid', activation=tf.nn.relu),
# 第二池化层
tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=(2,2), padding='same'),
# 扁平化层，将多维数据转换为一维数据。
tf.keras.layers.Flatten(),
# 全连接层
tf.keras.layers.Dense(units=120, activation=tf.nn.relu),
# 全连接层
tf.keras.layers.Dense(units=84, activation=tf.nn.relu),
# 输出层，全连接
tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)
])
# 优化器
adam_optimizer = tf.keras.optimizers.Adam(learning_rate)
# 编译模型
model.compile(optimizer=adam_optimizer,
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
# 模型开始训练时间
start_time = datetime.datetime.now()
# 训练模型
model.fit(x=x_train, y=train_label, batch_size=batch_size, epochs=num_epochs)
# 模型结束训练，记录训练时间
end_time = datetime.datetime.now()
time_cost = end_time - start_time```

## 模型的展示

`model.summary()`

## 对一张图片进行预测

```# 进行预测
image_index = 100  # 选一张图片
pred = model.predict(x_test[image_index].reshape(1,32,32,1))
print(pred.argmax())  # 打印出预测值
plt.imshow(x_test[image_index].reshape(32,32), cmap='Greys')
plt.show()```

`print(model.evaluate(x_test,  y_test, verbose=2))`