与MNIST类似,CIFAR-10同样是人工智能学习入门的数据集之一,它包含飞机、汽车、小鸟等10个类别的图片,一共60000张图片,其中训练集占50000张,测试集占10000张。
这里采用CNN网络对CIFAR-10数据集进行分类识别。
1 导入需要的模块
首先,导入需要用到的模块
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import models, layers
import matplotlib.pyplot as plt
2 载入数据
利用keras集成的数据集载入CIFAR-10数据集
# load CIFAR-10 dataset
(train_images, train_labels), (test_images, test_labels) = keras.datasets.cifar10.load_data()
# train_images: 50000*32*32*3, train_labels: 50000*1,
# test_images: 10000*32*32*3, test_labels: 10000*1
# change data shape & types
train_input = train_images.astype('float32')/255
test_input = test_images.astype('float32')/255
train_output = train_labels.astype('int16')
test_output = test_labels.astype('int16')
调用格式和mnist相同。生成train_images、train_labels、test_images、test_labels等四个变量,分别代表训练和测试图像和标记。其中图像数据的维度为Nx32x32x3,表示每张图片为32x32的彩色图片,每一个像素点由一个3维数据表示颜色。这里进行数据处理,把图像数据归一到0-1之间的浮点数。
3 构建模型
构建一个多层的CNN网络,定义构建函数
def build_model():
model = models.Sequential()
# first layer
model.add(layers.Conv2D(16, (3,3), padding='same', activation='relu', data_format='channels_last', input_shape=(32,32,3)))
model.add(layers.Conv2D(