在以往的手写数字识别中,数据集一共是70000张图片,模型准确率可以达到99%以上的准确率。而本次实验的手写数字数据集中有120000张图片,而且数据集的预处理方式也是之前没有遇到过的。最终在验证集上的模型准确率达到了99.1%。在模型训练过程中,加入了上一篇文章中提到的早停策略以及模型保存策略。
1.导入库
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import os,PIL,pathlib,warnings,pickle,png
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
2.数据处理
原始数据如下所示: 这是经过序列化的图片数据,因此需要我们自己反序列化,读入内存中
def unpickle(file):
with open(file,'rb') as fo:
dict = pickle.load(fo,encoding='bytes')
return dict
Qmnist = unpickle("E:/tmp/.keras/datasets/QMnist/MNIST-120k")
data = Qmnist['data']
labels = Qmnist['labels']
读入内存中的数据,需要转化为图片格式,按照它所属的标签,存放到不同的文件夹中。
num = data.shape[0]
if not os.path.exists('E:/tmp/.keras/datasets/QMnist/dataset'):
os.mkdir('E:/tmp/.keras/datasets/QMnist/dataset')
for i in range(0,num):
x = data[i]
y = str(labels[i])
name = str(i)
if not os.path.exists('E:/tmp/.keras/datasets/QMnist/dataset/{}'.format(y)):
os.mkdir('E:/tmp/.keras/datasets/QMnist/dataset/{}'.format(y))
最终处理出来的图片数据如下所示: 其中[4]中的部分图片如下所示:
3.划分训练集、测试集、验证集
这一部分属于老生常谈的问题了~
data_dir = "E:/tmp/.keras/datasets/QMnist/dataset"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.png')))
all_images_paths = list(data_dir.glob('*'))
all_images_paths = [str(path) for path in all_images_paths]
all_label_names = [path.split("\\")[5].split(".")[0] for path in all_images_paths]
height = 75
width = 75
batch_size = 8
epochs = 50
train_data_gen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
validation_split=0.2
)
train_ds = train_data_gen.flow_from_directory(
directory=data_dir,
target_size=(height,width),
batch_size=batch_size,
shuffle=True,
class_mode='categorical',
subset='training',
seed=42
)
validation_data_gen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
validation_split=0.2
)
val_ds = validation_data_gen.flow_from_directory(
directory=data_dir,
target_size=(height,width),
batch_size=batch_size,
shuffle=True,
class_mode='categorical',
subset='validation'
)
test_data_gen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
validation_split=0.1
)
test_ds = test_data_gen.flow_from_directory(
directory=data_dir,
target_size=(height,width),
batch_size=batch_size,
shuffle=True,
class_mode='categorical',
subset='validation'
)
经过处理之后,查看图片:
plt.figure(figsize=(15, 10))
for images, labels in train_ds:
for i in range(40):
ax = plt.subplot(5, 8, i + 1)
plt.imshow(images[i])
plt.title(all_label_names[np.argmax(labels[i])])
plt.axis("off")
break
plt.show()
4.网络搭建
一开始采用的是VGG16模型,但是跑的实在是太慢了,而且不知道哪方面出了问题,准确率很低。
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=32,kernel_size=(3,3),padding="same",activation="relu",input_shape=[64, 64, 3]),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(filters=64,kernel_size=(3,3),padding="same",activation="relu"),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(filters=64,kernel_size=(3,3),padding="same",activation="relu"),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax")
])
早停策略以及模型保存
Earlystop = tf.keras.callbacks.EarlyStopping(
monitor='loss',
mode='min',
restore_best_weights=True
)
Checkpoint = tf.keras.callbacks.ModelCheckpoint(
filepath='E:/Users/yqx/PycharmProjects/Qmnist/model.h5',
save_best_only=True,
monitor='val_accuracy',
mode='max'
)
网络编译&&训练
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs,
callbacks=[Earlystop,Checkpoint]
)
Accuracy以及Loss图如下所示: epochs设置的为50,但是在第7个epoch训练结束后,就停止了,实现了早停策略。
5.模型测试&&混淆矩阵
模型加载:
model = tf.keras.models.load_model('cloud/model.h5')
对测试集进行模型测试:
model.evaluate(test_ds)
最终结果如下所示:
1500/1500 [==============================] - 9s 6ms/step - loss: 0.0469 - accuracy: 0.9912
[0.046884261071681976, 0.9911637306213379]
绘制混淆矩阵:
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
import seaborn as sns
pred = model.predict(test_ds).argmax(axis=1)
labels = list(train_ds.class_indices.keys())
cm = confusion_matrix(test_data.classes, pred)
plt.figure(figsize=(15,10))
sns.heatmap(cm, annot=True, fmt='g', xticklabels=labels, yticklabels=labels, cmap="BuPu")
plt.title('Confusion Matrix')
plt.show()
努力加油a啊
|