import tensorflow as tf
import numpy as np
import math
import timeit
import matplotlib.pyplot as plt
import matplotlib
import os
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D


cifar10=tf.keras.datasets.cifar10.load_data()
(x_img_train, y_label_train), (x_img_test, y_label_test) = cifar10
label_dict = {0:'airplane', 1:'automobile', 2:"bird", 3:"cat", 4:"deer", 5:"dog",6:"frog", 7:"horse", 8:"ship", 9:"truck"}
x_img_train_normalize=x_img_train.astype('float32')/255
x_img_test_normalize=x_img_test.astype('float32')/255
y_label_train_OneHot=np_utils.to_categorical(y_label_train)
y_label_test_OneHot=np_utils.to_categorical(y_label_test)
model=Sequential()
model.add(Conv2D(filters=32,
                 kernel_size=(3,3),
                 padding='same',
                 input_shape=(32,32,3),
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=64,
                 kernel_size=(3,3),
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=128,
                 kernel_size=(3,3),
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=256,
                 kernel_size=(3,3),
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dropout(0.25))
model.add(Dense(1024,activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(10,activation='softmax'))

#查看模型摘要
print(model.summary())

使用 Keras + CNN 识别 CIFAR-10 照片图像

 

训练模型,迭代50次:

model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
train_history = model.fit(x=x_img_train_normalize,
                        y=y_label_train_OneHot,
                        validation_split = 0.2,
                        epochs=50,
                        batch_size=256,
                        verbose=2)

使用 Keras + CNN 识别 CIFAR-10 照片图像

查看训练模型loss和accuracy:

def show_train_history(train_history,train,validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train History')
    plt.ylabel(train)
    plt.xlabel('Epoach')
    plt.legend(['train','validation'],loc='upper left')
    plt.show()
show_train_history(train_history,'loss','val_loss')
show_train_history(train_history,'accuracy','val_accuracy')

使用 Keras + CNN 识别 CIFAR-10 照片图像

精度图像如下所示:

使用 Keras + CNN 识别 CIFAR-10 照片图像

评估模型:

用测试集来验证模型好坏,50次迭代准确度为79.75%。可以继续调节卷积层,池化层,隐藏层,数据集批量大小,迭代次数来提高模型准确度。

scores=model.evaluate(x_img_test_normalize,y_label_test_OneHot)
print(scores[1])

使用 Keras + CNN 识别 CIFAR-10 照片图像

预测模型:

#预测第一个图片
prediction=np.argmax(model.predict(x_img_test_normalize[:1]))
print('第一个图片预测值: ',label_dict[prediction])
print("第一个图片真实值: ",label_dict[np.argmax(y_label_test_OneHot[:1])])

使用 Keras + CNN 识别 CIFAR-10 照片图像

#预测第二个图片
prediction=np.argmax(model.predict(x_img_test_normalize[1:2]))
print('第一个图片预测值: ',label_dict[prediction])
print("第一个图片真实值: ",label_dict[np.argmax(y_label_test_OneHot[1:2])])

使用 Keras + CNN 识别 CIFAR-10 照片图像