CIF100实战(VGG13)

CIFAR-100 数据集就像CIFAR-10,除了它有100个类,每个类包含600个图像。,每类各有500个训练图像和100个测试图像。CIFAR-100 中的100个类被分成20个超类。每个图像都带有一个精细标签(它所属的类)和一个粗糙标签(它所属的超类)

   

这里使用比较强大的经典网络结构VGG13,根据数据集特点修改部分网络结构,完成 CIFAR100 图片识别。调整后的VGG13网络模型:

一、数据集加载以及数据集预处理

# 预处理
def preprocess(x, y):
    # x :[-1,1]
    x = 2 * tf.cast(x, dtype=tf.float32) / 255 - 1
    y = tf.cast(y, dtype=tf.int32)
    return x, y


# 数据集加载
(x, y), (x_text, y_text) = datasets.cifar100.load_data()
print("y:",y.shape)
# 压缩最后一个维度为1
y = tf.squeeze(y)
y_text = tf.squeeze(y_text, axis=1)
print('squeeze:',x.shape, y.shape, x_text.shape, y_text.shape)


# 创建batch
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.map(preprocess).shuffle(1000).batch(128)

test_db = tf.data.Dataset.from_tensor_slices((x, y))
test_db = test_db.map(preprocess).batch(128)

# 获取下一个batch
sample = next(iter(test_db))
print('sample:', sample[0].shape, sample[1].shape,
      tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))

数据集的处理和CIF10的处理是一样的,这里也要将y进行维度压缩如下。将维度为1的压缩,为one_hot编码做准备

 上述代码运行后,得到训练集的𝑿和𝒚形状为:(50000, 32, 32, 3)和(50000),测试集的𝑿和𝒚形状为(10000, 32, 32, 3)和(10000),分别代表了图片大小为32 × 32,彩色图片,训练集样本数为 50000,测试集样本数为 10000

二、网络模型构建与装配

将网络实现为 2 个子网络:卷积子网络全连接子网络。卷积子网络由 5 个子模块构成,每个子模块包含了 Conv-Conv-MaxPooling 单元结构


conv_layers = [  # 5 units : conv + conv + max pooling
    # units1  64个3x3 卷积核, 输入输出同大小
    layers.Conv2D(64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    # 高宽减半
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 2 由于上一层池化层减半,下一层将卷积层的卷积核翻一倍,为了弥补信息特征的减少
    layers.Conv2D(128, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(128, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 3
    layers.Conv2D(256, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(256, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 4
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 5
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same')
]

一般在上一个池化层进行最大化采用后(pool_size=[2,2] ,s=2),降低了网络的参数量,得到的信息特征后减半在进行下一个卷积层的时会将卷积核的倍数翻倍,以弥补信息的减少

# [b,32,32,3] => [b,1,1,512]
    conv_net = Sequential(conv_layers)

    fc_net = Sequential([
        layers.Dense(256, activation=tf.nn.relu),
        layers.Dense(128, activation=tf.nn.relu),
        layers.Dense(10, activation=None)
    ])

    conv_net.build(input_shape=[None, 32, 32, 3])
    fc_net.build(input_shape=[None, 512])
    conv_net.summary()
    fc_net.summary()
    optimizer = optimizers.Adam(learning_rate=1e-4)

    # 可训练的变量 两个网络层之和
    variables = conv_net.trainable_variables + fc_net.trainable_variables

全连接子网络包含了 3 个全连接层,每层添加 ReLU 非线性激活函数,最后一层除外。卷积子网层输入的就是一张图片大小的维度[32,32,3], 不像全连接层那样需要打平层一维的。但是在进行两层的连接时,需要将卷积子网层打平成一维的。

设置优化器,注意需要将两层的可训练变量加起来。

三、梯度计算与参数更新

      for step, (x, y) in enumerate(train_db):
            # 梯度求导
            with tf.GradientTape() as tape:
                # [b, 32,32,3 ] =>[b,1,1,512]
                out = conv_net(x)
                out = tf.reshape(out, [-1, 512])

                # [b, 512] => [b, 10]
                logits = fc_net(out)
                # [b,10] =>
                y_onehot = tf.one_hot(y, depth=10)
                # loss
                loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
                loss = tf.reduce_mean(loss)
            # 求导
            grads = tape.gradient(loss, variables)
            # 更新参数
            optimizer.apply_gradients(zip(grads, variables))

            if step % 100 == 0:
                print(epoch, step, 'loss', float(loss))

在全连接层进行向前计算的时,需要将卷积子层的输出进行打平,其余都和前面的一样

四、测试

  # 测试集
        total_num = 0
        total_correct = 0
        for x, y in test_db:
            out = conv_net(x)
            out = tf.reshape(out, [-1, 512])
            logits = fc_net(out)
            prob = tf.nn.softmax(logits, axis=1)  # 概率化,和为1
            pred = tf.argmax(prob, axis=1)  # 获得最大下标
            pred = tf.cast(pred, dtype=tf.int32)

            correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)  # 测试值与真实值比较
            correct = tf.reduce_sum(correct)        # 统计正确的

            total_num += x.shape[0]  # 样本数
            total_correct += int(correct)
        acc = total_correct / total_num
        print(epoch, 'acc', acc)

数据集的形状十分重要,无论是加载后数据集还是要预处理的数据集,都应确保其 shape 准确,否则无法代入网络进行训练

若三,四步有看不懂的地方,可以参考mnist数据集实战那篇文章哦!
 

五、完整程序

# -*- codeing = utf-8 -*-
# @Time : 16:15
# @Author:Paranipd
# @File : cifar100_test.py
# @Software:PyCharm

import tensorflow as tf
from tensorflow.keras import layers, Sequential, datasets, optimizers
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

tf.random.set_seed(2345)

# 预处理
def preprocess(x, y):
    # x :[-1,1]
    x = 2 * tf.cast(x, dtype=tf.float32) / 255 - 1
    y = tf.cast(y, dtype=tf.int32)
    return x, y


# 数据集加载
(x, y), (x_text, y_text) = datasets.cifar100.load_data()
print("y:",y.shape)
# 压缩最后一个维度为1
y = tf.squeeze(y)
y_text = tf.squeeze(y_text, axis=1)
print('squeeze:',x.shape, y.shape, x_text.shape, y_text.shape)


# 创建batch
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.map(preprocess).shuffle(1000).batch(128)

test_db = tf.data.Dataset.from_tensor_slices((x, y))
test_db = test_db.map(preprocess).batch(128)

# 获取下一个batch
sample = next(iter(test_db))
print('sample:', sample[0].shape, sample[1].shape,
      tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))


conv_layers = [  # 5 units : conv + conv + max pooling
    # units1  64个3x3 卷积核, 输入输出同大小
    layers.Conv2D(64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    # 高宽减半
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 2 由于上一层池化层减半,下一层将卷积层的卷积核翻一倍,为了弥补信息特征的减少
    layers.Conv2D(128, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(128, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 3
    layers.Conv2D(256, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(256, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 4
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),

    # units 5
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.Conv2D(512, kernel_size=[3, 3], padding='same', activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same')
]


def main():

    # [b,32,32,3] => [b,1,1,512]
    conv_net = Sequential(conv_layers)

    fc_net = Sequential([
        layers.Dense(256, activation=tf.nn.relu),
        layers.Dense(128, activation=tf.nn.relu),
        layers.Dense(10, activation=None)
    ])

    conv_net.build(input_shape=[None, 32, 32, 3])
    fc_net.build(input_shape=[None, 512])
    conv_net.summary()
    fc_net.summary()
    optimizer = optimizers.Adam(learning_rate=1e-4)

    # 可训练的变量 两个网络层之和
    variables = conv_net.trainable_variables + fc_net.trainable_variables

    for epoch in range(50):
        for step, (x, y) in enumerate(train_db):
            # 梯度求导
            with tf.GradientTape() as tape:
                # [b, 32,32,3 ] =>[b,1,1,512]
                out = conv_net(x)
                out = tf.reshape(out, [-1, 512])

                # [b, 512] => [b, 10]
                logits = fc_net(out)
                # [b,10] =>
                y_onehot = tf.one_hot(y, depth=10)
                # loss
                loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
                loss = tf.reduce_mean(loss)
            # 求导
            grads = tape.gradient(loss, variables)
            # 更新参数
            optimizer.apply_gradients(zip(grads, variables))

            if step % 100 == 0:
                print(epoch, step, 'loss', float(loss))

        # 测试集
        total_num = 0
        total_correct = 0
        for x, y in test_db:
            out = conv_net(x)
            out = tf.reshape(out, [-1, 512])
            logits = fc_net(out)
            prob = tf.nn.softmax(logits, axis=1)  # 概率化,和为1
            pred = tf.argmax(prob, axis=1)  # 获得最大下标
            pred = tf.cast(pred, dtype=tf.int32)

            correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)  # 测试值与真实值比较
            correct = tf.reduce_sum(correct)        # 统计正确的

            total_num += x.shape[0]  # 样本数
            total_correct += int(correct)
        acc = total_correct / total_num
        print(epoch, 'acc', acc)


if __name__ == '__main__':
    main()






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Super.Bear

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值