简介
**本文使用keras(2.1.4)----其他版本有坑. 网络框架搭建CNN网络,对cifar10数据集进行图像识别,cifar10是一种自带label的图像数据集,数据集种类十分丰富可以很好的检验网络性能,话不多说直接进入正题 **
第一步获取数据集
通过keras可以直接下载cifar10数据集(数据集比较大可能需要一些时间)
import keras
#使用cifar10数据集
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
展示前24张图片
观察数据集的部分样本别问为什么,要有一个程序员的严谨!!严谨!!严谨!!(重要的事说3遍)
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20,5))
for i in range(36):
ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_train[i]))
所有数据集除以255重构图像
因为图像单个像素中最大值为255,将其除以255是将每一个像素缩放到0-1之间,类似于标准化
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
将数据分解为测试集、训练集、验证集
from keras.utils import np_utils
# 将标签转化为one-hot
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# 将数据分解为训练集和测试集
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# 输出训练集形状
print('x_train shape:', x_train.shape)
# 输出每一个集合的长度
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')
开始构建卷积神经网络
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
#初始化网络类型,选择顺序网络
model = Sequential()
#添加卷积层,使用same填充,relu激活
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu',
input_shape=(32, 32, 3)))
#添加池化层
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
#舍弃部分神经元,避免过拟合
model.add(Dropout(0.3))
#数据扁平化
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))
#模型确认
model.summary()
#模型启动,定义损失函数,优化器,评分标准
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
模型训练开始!
心疼一波没有GPU的小伙伴。。。
from keras.callbacks import ModelCheckpoint
#训练模型
checkpointer = ModelCheckpoint(filepath='model.weights.best.hdf5', verbose=1,
save_best_only=True)
hist = model.fit(x_train, y_train, batch_size=32, epochs=100,
validation_data=(x_valid, y_valid), callbacks=[checkpointer],
verbose=2, shuffle=True)
测试集预测
终于到了激动人心的时刻,想不想知道自己搭建的模型的性能? 等着吧!
# 获取训练集预测
y_hat = model.predict(x_test)
# 定义文本标签--来源:(source: https://www.cs.toronto.edu/~kriz/cifar.html)
cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
结果展示!!!!!
# 展示样本训练结果
fig = plt.figure(figsize=(20, 8))
for i, idx in enumerate(np.random.choice(x_test.shape[0], size=32, replace=False)):
ax = fig.add_subplot(4, 8, i + 1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_test[idx]))
pred_idx = np.argmax(y_hat[idx])
true_idx = np.argmax(y_test[idx])
ax.set_title("{} ({})".format(cifar10_labels[pred_idx], cifar10_labels[true_idx]),
color=("green" if pred_idx == true_idx else "red"))
感言:
说实话图像识别的发展是一个很漫长的过程,通过结果可以发现有时候我们确实有点为难机器了,不信你们自己看看那训练结果。。 有些图片你自己都不知道是什么东西。。 还有一点 感谢各位的支持 !拜拜?!
还没完。 没有GPU的小伙伴可以去亚马逊申请免费的GPU服务器后 嘿嘿?
最后像提供数据集的前辈们致敬!