Tensorflow2----VGG13

该博客介绍了如何使用TensorFlow构建VGG13模型,并对CIFAR10数据集进行预处理、训练和验证。首先,加载CIFAR10数据,进行数据预处理,然后构建VGG13网络结构,包括多个卷积层和池化层。接着,创建全连接层子网络,并将两个子网络连接在一起。通过Adam优化器进行模型训练,每100步记录并输出损失函数结果,同时在测试集上验证模型性能,输出测试集的准确率。
摘要由CSDN通过智能技术生成

CIFAR10

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets, Sequential,losses
# 一 加载CIFAR10数据集
(x,y), (x_test, y_test) = datasets.cifar10.load_data()
# x的shape为(50000, 32, 32, 3) y的shape为(50000, 1),x_test的shape为(10000, 32, 32, 3),y_test的shape为(10000, 1)
# y的类别有100个,删除y的一个维度,[b,1] => [b]
y = tf.squeeze(y, axis=1)
y_test = tf.squeeze(y_test, axis=1)
print(x.shape, y.shape, x_test.shape, y_test.shape)
# 构建预处理函数
def preprocess(x, y):
    # [0~1] 并将x的数值精度变为float32,y为int32
    x = 2*tf.cast(x, dtype=tf.float32) / 255.-1
    # x = tf.cast(x, dtype=tf.float32) / 255.
    y = tf.cast(y, dtype=tf.int32)
    return x,y
# 训练集预处理
train_db = tf.data.Dataset.from_tensor_slices((x,y))
train_db = train_db.shuffle(50000).map(preprocess).batch(128)
# 训练20个epoch
# train_db = train_db.repeat(20)
# 测试集预处理
test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test))
test_db = test_db.map(preprocess).batch(64)
# 从训练集中采样一个Batch,观察其结构
sample = next(iter(train_db))
print("sample:", sample[0].shape, sample[1].shape,
      tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))

# 二 构造VGG13模型
def main():
    # 创建包含多层卷积层的列表
        conv_layers = [
        # Conv-Conv-Pooling单元1 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'),

        # Conv-Conv-Pooling单元2,输出通道提升至128,高宽大小减半
        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'),

        # Conv-Conv-Pooling单元3,输出通道提升至256,高宽大小减半
        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'),

        # Conv-Conv-Pooling单元4,输出通道提升至512,高宽大小减半
        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'),

        # Conv-Conv-Pooling单元5,输出通道提升至512,高宽大小减半
        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')
        ]
        # 利用前面创建的层列表构建网络容器
        conv_net = Sequential(conv_layers)

        # 创建3层全连接层子网络
        fc_net = Sequential([
        layers.Flatten(),
        layers.Dense(256, activation=tf.nn.relu),
        layers.Dense(128, activation=tf.nn.relu),
        layers.Dense(10, activation=None),
        ])
        # build2个子网络,并打印网络参数信息
        conv_net.build(input_shape=[4, 32, 32, 3])
        fc_net.build(input_shape=[4, 512])
        conv_net.summary()
        fc_net.summary()
        # 列表合并,合并2个子网络的参数
        variables = conv_net.trainable_variables + fc_net.trainable_variables
        # variables = fc_net.trainable_variables
        loss_all = []
        # 创建损失函数的类,在实际计算时直接调用类实例即可
        criteon = losses.CategoricalCrossentropy(from_logits=True)
        for epoch in range(300):
            for step, (x, y) in enumerate(train_db):
                with tf.GradientTape() as tape:
                    out_1 = conv_net(x)
                    out_2 = fc_net(out_1)
                    # one-hot编码
                    y = tf.one_hot(y, depth=10)
                    # 计算交叉熵损失函数,标量
                    loss = criteon(y, out_2)
                # 自动计算梯度,关键看如何表示待优化变量
                grads = tape.gradient(loss, variables)
                # 自动更新参数
                optimizer = optimizers.Adam(lr=1e-4)
                optimizer.apply_gradients(zip(grads, variables))
                # step为100次时,记录并输出损失函数结果
                if step % 100 == 0:
                    print(step, 'loss:', float(loss))
                    loss_all.append(float(loss))
                # step为100次时,用测试集验证模型
                if step % 100 == 0:
                    total, total_correct = 0., 0
                    correct, total = 0, 0
                    for x, y in test_db:
                        out_1 = conv_net(x)
                        out = fc_net(out_1)
                        # 前向计算,获得10类别的预测分布,[b, 1064] => [b, 10]
                        # 真实的流程时先经过softmax,再argmax,但是由于softmax不改变元素的大小相对关系,故省去
                        pred = tf.argmax(out, axis=-1)
                        y = tf.cast(y, tf.int64)
                        # 统计预测正确数量
                        correct += float(tf.reduce_sum(tf.cast(tf.equal(pred, y), tf.float32)))
                        # 统计预测样本总数
                        total += x.shape[0]
                    # 计算准确率
                    print('test acc:', correct / total)

if __name__== '__main__' :
    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        try:
            # Currently, memory growth needs to be the same across GPUs
            for gpu in gpus:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            print(e)

    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值