人工智能学习:CIFAR-10数据分类识别(4)

2023-05-16

与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(16, (3,3), padding='same', activation='relu'))
    model.add(layers.MaxPooling2D((2,2)))
    
    # second layer
    model.add(layers.Conv2D(32, (3,3), padding='same', activation='relu'))
    model.add(layers.Conv2D(32, (3,3), padding='same', activation='relu'))
    model.add(layers.MaxPooling2D((2,2)))

    # third layer, flatten
    model.add(layers.Flatten())
    
    # fourth layer
    model.add(layers.Dense(128, activation='relu'))
    model.add(layers.Dense(10, activation='softmax'))
    
    model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['sparse_categorical_accuracy'])
    
    return model

构建模型如下

# build model
network = build_model()

# show network summary
network.summary()

输出模型的结构,如下

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 32, 32, 16)        448       
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 32, 32, 16)        2320      
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 16, 16, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 16, 16, 32)        4640      
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 16, 16, 32)        9248      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 8, 8, 32)          0         
_________________________________________________________________
flatten (Flatten)            (None, 2048)              0         
_________________________________________________________________
dense (Dense)                (None, 128)               262272    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1290      
=================================================================
Total params: 280,218
Trainable params: 280,218
Non-trainable params: 0

4 训练模型
调用训练模型函数

# train model
history = network.fit(train_input, train_output, epochs=20, batch_size=64, validation_split=0.2)

显示结果

Epoch 1/20
625/625 [==============================] - 6s 5ms/step - loss: 1.5318 - sparse_categorical_accuracy: 0.4451 - val_loss: 1.2786 - val_sparse_categorical_accuracy: 0.5455
Epoch 2/20
625/625 [==============================] - 2s 4ms/step - loss: 1.1113 - sparse_categorical_accuracy: 0.6072 - val_loss: 1.0753 - val_sparse_categorical_accuracy: 0.6193
Epoch 3/20
625/625 [==============================] - 2s 4ms/step - loss: 0.9271 - sparse_categorical_accuracy: 0.6734 - val_loss: 0.9335 - val_sparse_categorical_accuracy: 0.6716
Epoch 4/20
625/625 [==============================] - 2s 4ms/step - loss: 0.8096 - sparse_categorical_accuracy: 0.7171 - val_loss: 0.8828 - val_sparse_categorical_accuracy: 0.6968
Epoch 5/20
625/625 [==============================] - 2s 4ms/step - loss: 0.7269 - sparse_categorical_accuracy: 0.7457 - val_loss: 0.8725 - val_sparse_categorical_accuracy: 0.7000

...
Epoch 19/20
625/625 [==============================] - 2s 4ms/step - loss: 0.0986 - sparse_categorical_accuracy: 0.9653 - val_loss: 1.8485 - val_sparse_categorical_accuracy: 0.7065
Epoch 20/20
625/625 [==============================] - 2s 4ms/step - loss: 0.0917 - sparse_categorical_accuracy: 0.9673 - val_loss: 1.9127 - val_sparse_categorical_accuracy: 0.7050

训练过程的变量包含在返回变量history中,绘制训练过程如下

# plot train history
loss = history.history['loss']
val_loss = history.history['val_loss']
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']

plt.figure(figsize=(10,3))

plt.subplot(1,2,1)
plt.plot(loss, color='blue', label='train')
plt.plot(val_loss, color='red', label='test')
plt.ylabel('loss')
plt.legend()

plt.subplot(1,2,2)
plt.plot(acc, color='blue', label='train')
plt.plot(val_acc, color='red', label='test')
plt.ylabel('accuracy')
plt.legend()

显示结果如下
在这里插入图片描述

分别绘制了训练阶段和测试阶段的分类识别精度和损失函数,蓝线表示训练阶段的损失函数和准确度,红线表示测试阶段的损失函数和准确度。结果显示通过训练,神经网络模型在训练集上的表现性能越来越好,但是在测试集上的识别准确度并没有提升,相反损失函数反而变大。说面模型训练出现过拟合的情况,泛化能力较差。

5 评估模型
评估训练后模型的性能,如下

# evaluate model
network.evaluate(test_input, test_output, verbose=2)

显示结果

313/313 - 1s - loss: 2.0248 - sparse_categorical_accuracy: 0.6923
[2.02479887008667, 0.692300021648407]

在测试集上的准确度为0.6923。
在这里绘制测试集前100张图片的识别结果

# predict on test data
predict_output = network.predict(test_input)

# lines and columns of subplots
m = 10
n = 10
num = m*n

# labels of category
labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

# figure size
plt.figure(figsize=(15,15))

# plot first 100 pictures and results in test images
for i in range(num):
    plt.subplot(m,n,i+1)
    
    type_index = np.argmax(predict_output[i]);
    label = labels[type_index]
    
    clr = 'black' if type_index == test_labels[i] else 'red'
                 
    plt.imshow(test_images[i])
    plt.xticks([])
    plt.yticks([])
    
    plt.xlabel(label, color=clr)

plt.show()

在这里插入图片描述

黑色字体表示正确的识别,红色字体表示错误的识别,结果显示,在测试集前100张图片的识别中,大概还有30%左右的误识别率。也证明了前面的评估结果。说明了这个模型的泛化能力不足。还需要优化模型参数和结构。

参考链接:https://blog.csdn.net/weixin_45954454/article/details/114519299

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

人工智能学习:CIFAR-10数据分类识别(4) 的相关文章

随机推荐

  • Jetson Nano设置风扇自启动

    Jetson Nano跑一些如目标识别等需要较大计算量的程序 xff0c 散热板会非常的热 xff0c 为避免主板过热 xff0c 通常在散热板上加装一个风扇增强散热 风扇需要软件指令进行驱动 xff0c 驱动风扇的指令为 sudo sh
  • Ubuntu 18.04安装gazebo9

    首先 xff0c 把gazebo的源添加到apt的source list中 sudo sh c echo deb http packages osrfoundation org gazebo ubuntu stable 96 lsb rel
  • 问题解决:/usr/bin/ld: cannot find -lbz2

    在项目编译过程中 xff0c 出现类似如下的错误 usr bin ld cannot find lbz2 经查询 xff0c 是找不到bz2的库文件 xff0c 用whereis命令查询 whereis libbz2 找不到对应的库文件 x
  • 常用Git命令

    通过git命令可以对项目代码库执行克隆 拉取 提交等操作 常用的git命令有如下 git clone 克隆代码库 xff0c 把远程代码库克隆到本机当前目录 xff0c 如 git clone https github com PX4 PX
  • 【Android】原来Toolbar还能这么用?Toolbar使用最全解析。网友:终于不用老是自定义标题栏啦

    一个Toolbar的UI可以做成什么样 xff1f 做出什么效果 xff1f 这是我最近在研究的问题 目录 带导航图标的Toolbar带标题的Toolbar带小标题的Toolbar带Logo的Toolbar带进度条的Toolbar带菜单的T
  • Linux安装Beyond Compare

    Beyond Compare是一款很好用的代码比对软件 xff0c 提供了在Windows xff0c Linux等平台的安装包 在Linux下安装Beyond Compare的方法如下 参考链接 xff1a https www scoot
  • Linux下压缩解压文件和目录的方法(zip, tar)

    Linux下可以用zip命令方便的压缩文件或文件夹 压缩文件 zip data zip data xls zip data zip data1 xls data2 xls 上述命令把一个文件或者多个文件压缩到一个zip文件 压缩目录 zip
  • Jupyter Notebook安装

    Jupyter Notebook是一个非常好用的交互式Python运行的软件 安装方法如下 在命令行输入 pip3 install jupyter 安装后根据提示 xff0c Jupyter相关软件安装在 local bin目录下 xff0
  • Ubuntu添加截屏快捷键的方法

    在Ubuntu下面具有截屏的命令 xff08 gnome screenshot xff09 xff0c 可以通过简单的设置方便的添加截屏快捷键 通过 Settings gt Devices gt Keyboard选项 xff0c 添加快捷键
  • Windows下修改Jupyter Notebook默认字体的方法(custom.css)

    在Windows下Jupyter Notebook代码显示的默认字体为宋体 xff0c 视觉效果不是很好 xff0c 可以通过设置修改默认的显示字体 通过用户目录 C User Administrator jupyter custom 下的
  • Jupyter Notebook添加代码自动补全功能的方法

    Jupyter Notebook成为一款非常受欢迎的交互式Python运行环境的软件 通过如下的方法可以添加代码自动补全的功能 输入命令安装插件 pip3 install jupyter contrib nbextensions 然后运行
  • 修改grub默认启动选项的方法

    在Windows系统基础上 xff0c 再安装Linux xff0c 形成双系统 这样在grub启动菜单中会包含Linux Windows等多个选项 xff0c 默认为第一个选项 xff0c 常规的Linux启动 通过修改配置文件 etc
  • 在云服务器上搭建Jupyter Notebook服务

    Jupyter Notebook提供了远程登录的功能 xff0c 可以在云服务器上配置Jupyter Notebook xff0c 用户可以远程登录和运行Python代码 这里使用的是腾讯云的Ubuntu服务器 xff0c 配置方法如下 1
  • 常用Linux命令

    记录一些常用的Linux命令 1 用户管理 增加用户 useradd lt user name gt useradd g lt group name gt lt user name gt g选项指定新用户所属的用户组 修改用户的组别 use
  • 在云服务器上安装VNC远程桌面服务

    云服务器操作系统通常不包含图形界面 xff0c 通过在服务器上安装VNC服务 xff0c 可以让用户以图形化界面远程登录到云服务器 这里服务器使用的是Ubuntu Server 18 04系统 1 安装图形界面 首先在服务器端安装图形化桌面
  • 【Android】ADB无线连接Android设备

    目录 简介无线连接的条件adb连接设备方法一方法二 修改端口号方法一方法二 辅助工具android toolscrcpy gui 问题集合 简介 Android Debug Bridge xff0c 简称adb xff0c 是一种功能多样的
  • 人工智能学习:载入MNIST数据集(1)

    MNIST数据集是人工智能学习入门的数据集 xff0c 包含了一系列的手写的数字图片 载入MNIST数据集的方法很简单 xff0c Tensorflow集成了载入数据集的方法 首先导入tensorflow模块和matplotlib pypl
  • 人工智能学习:MNIST数据分类识别神经网络(2)

    在MNIST数据集上构建一个神经网络 xff0c 进行训练 xff0c 以达到良好的识别效果 1 导入模块 首先 xff0c 导入必要的模块 span class token keyword import span numpy span c
  • 人工智能学习:NMIST数据分类识别-CNN网络(3)

    这里采用CNN模型 xff08 卷积神经网络 xff09 来进行MNIST数据集的分类识别 1 导入模块 首先 xff0c 导入需要的模块 span class token keyword import span numpy span cl
  • 人工智能学习:CIFAR-10数据分类识别(4)

    与MNIST类似 xff0c CIFAR 10同样是人工智能学习入门的数据集之一 xff0c 它包含飞机 汽车 小鸟等10个类别的图片 xff0c 一共60000张图片 xff0c 其中训练集占50000张 xff0c 测试集占10000张