Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
高层 API 实现 RepVGG 模型微调_创想鸟

高层 API 实现 RepVGG 模型微调

本文介绍如何用Paddle 2.0高层API微调RepVGG模型。先导入必要包,构建RepVGG模型及模块,封装模型预设配置,通过paddle.Model配置模型,加载Cifar10数据集,经训练后用model.predict_batch对图片预测,还可借助VisualDL可视化训练数据。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

高层 api 实现 repvgg 模型微调 - 创想鸟

引入

上一个项目介绍了【如何构建 RepVGG 模型】自从去年底尝试过高层 API 的使用之后,就没怎么使用过这个功能了Paddle 2.0 正式版更新之后,高层 API 功能也更加完善了所以,本次就介绍如何使用高层 API 完成 RepVGG 模型微调

相关项目

Paddle 2.0 图像分类微调的相关项目PaddleClas:复现 Vision Transformer 实现鲜花图像分类任务的微调PaddleHub:十行代码完成图像分类任务的微调PaddleHapi:高层 API 实现 RepVGG 模型微调

开始

废话少说,直接开始

准备

导入必要的包可选择开启静态图模式In [1]

# 导入 Paddleimport paddleimport paddle.nn as nnfrom paddle.static import InputSpecfrom paddle.vision.datasets import Cifar10from paddle.vision.transforms import Resize, CenterCrop, Transpose, Normalize, Compose# 导入其他包import cv2import numpy as npfrom IPython.display import Image# 开启静态图# 也可以直接用动态图进行模型训练paddle.enable_static()

   

模型组网

常规的继承 paddle.nn.Layer 来进行模型组网更多细节请参考【如何构建 RepVGG 模型】In [2]

# 卷积 + 批归一化class ConvBN(nn.Layer):    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, groups=1):        super(ConvBN, self).__init__()        self.conv = nn.Conv2D(in_channels=in_channels, out_channels=out_channels,                              kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias_attr=False)        self.bn = nn.BatchNorm2D(num_features=out_channels)    def forward(self, x):        y = self.conv(x)        y = self.bn(y)        return y# RepVGG 模块class RepVGGBlock(nn.Layer):    def __init__(self, in_channels, out_channels, kernel_size,                 stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros'):        super(RepVGGBlock, self).__init__()        self.in_channels = in_channels        self.out_channels = out_channels        self.kernel_size = kernel_size        self.stride = stride        self.padding = padding        self.dilation = dilation        self.groups = groups        self.padding_mode = padding_mode        assert kernel_size == 3        assert padding == 1        padding_11 = padding - kernel_size // 2        self.nonlinearity = nn.ReLU()        self.rbr_identity = nn.BatchNorm2D(            num_features=in_channels) if out_channels == in_channels and stride == 1 else None        self.rbr_dense = ConvBN(in_channels=in_channels, out_channels=out_channels,                                kernel_size=kernel_size, stride=stride, padding=padding, groups=groups)        self.rbr_1x1 = ConvBN(in_channels=in_channels, out_channels=out_channels,                              kernel_size=1, stride=stride, padding=padding_11, groups=groups)    def forward(self, inputs):        if not self.training:            return self.nonlinearity(self.rbr_reparam(inputs))        if self.rbr_identity is None:            id_out = 0        else:            id_out = self.rbr_identity(inputs)        return self.nonlinearity(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)    def eval(self):        if not hasattr(self, 'rbr_reparam'):            self.rbr_reparam = nn.Conv2D(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=self.kernel_size, stride=self.stride,                                         padding=self.padding, dilation=self.dilation, groups=self.groups, padding_mode=self.padding_mode)        self.training = False        kernel, bias = self.get_equivalent_kernel_bias()        self.rbr_reparam.weight.set_value(kernel)        self.rbr_reparam.bias.set_value(bias)        for layer in self.sublayers():            layer.eval()    def get_equivalent_kernel_bias(self):        kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)        kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)        return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid    def _pad_1x1_to_3x3_tensor(self, kernel1x1):        if kernel1x1 is None:            return 0        else:            return nn.functional.pad(kernel1x1, [1, 1, 1, 1])    def _fuse_bn_tensor(self, branch):        if branch is None:            return 0, 0        if isinstance(branch, ConvBN):            kernel = branch.conv.weight            running_mean = branch.bn._mean            running_var = branch.bn._variance            gamma = branch.bn.weight            beta = branch.bn.bias            eps = branch.bn._epsilon        else:            assert isinstance(branch, nn.BatchNorm2D)            if not hasattr(self, 'id_tensor'):                input_dim = self.in_channels // self.groups                kernel_value = np.zeros(                    (self.in_channels, input_dim, 3, 3), dtype=np.float32)                for i in range(self.in_channels):                    kernel_value[i, i % input_dim, 1, 1] = 1                self.id_tensor = paddle.to_tensor(kernel_value)            kernel = self.id_tensor            running_mean = branch._mean            running_var = branch._variance            gamma = branch.weight            beta = branch.bias            eps = branch._epsilon        std = (running_var + eps).sqrt()        t = (gamma / std).reshape((-1, 1, 1, 1))        return kernel * t, beta - running_mean * gamma / std# RepVGG 模型class RepVGG(nn.Layer):    def __init__(self, num_blocks, width_multiplier=None, override_groups_map=None, in_channels=3, class_dim=1000):        super(RepVGG, self).__init__()        assert len(width_multiplier) == 4        self.override_groups_map = override_groups_map or dict()        assert 0 not in self.override_groups_map        self.in_planes = min(64, int(64 * width_multiplier[0]))        self.stage0 = RepVGGBlock(            in_channels=in_channels, out_channels=self.in_planes, kernel_size=3, stride=2, padding=1)        self.cur_layer_idx = 1        self.stage1 = self._make_stage(            int(64 * width_multiplier[0]), num_blocks[0], stride=2)        self.stage2 = self._make_stage(            int(128 * width_multiplier[1]), num_blocks[1], stride=2)        self.stage3 = self._make_stage(            int(256 * width_multiplier[2]), num_blocks[2], stride=2)        self.stage4 = self._make_stage(            int(512 * width_multiplier[3]), num_blocks[3], stride=2)        self.gap = nn.AdaptiveAvgPool2D(output_size=1)        self.linear = nn.Linear(int(512 * width_multiplier[3]), class_dim)    def _make_stage(self, planes, num_blocks, stride):        strides = [stride] + [1]*(num_blocks-1)        blocks = []        for stride in strides:            cur_groups = self.override_groups_map.get(self.cur_layer_idx, 1)            blocks.append(RepVGGBlock(in_channels=self.in_planes, out_channels=planes, kernel_size=3,                                      stride=stride, padding=1, groups=cur_groups))            self.in_planes = planes            self.cur_layer_idx += 1        return nn.Sequential(*blocks)    def forward(self, x):        out = self.stage0(x)        out = self.stage1(out)        out = self.stage2(out)        out = self.stage3(out)        out = self.stage4(out)        out = self.gap(out)        out = paddle.flatten(out, start_axis=1)        out = self.linear(out)        return out

   

模型封装

使用函数形式将模型进行封装,将预设配置固定In [3]

# 模型超参数配置optional_groupwise_layers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26]g2_map = {l: 2 for l in optional_groupwise_layers}g4_map = {l: 4 for l in optional_groupwise_layers}# 各种模型预设配置def RepVGG_A0(**kwargs):    return RepVGG(num_blocks=[2, 4, 14, 1], width_multiplier=[0.75, 0.75, 0.75, 2.5], override_groups_map=None, **kwargs)def RepVGG_A1(**kwargs):    return RepVGG(num_blocks=[2, 4, 14, 1], width_multiplier=[1, 1, 1, 2.5], override_groups_map=None, **kwargs)def RepVGG_A2(**kwargs):    return RepVGG(num_blocks=[2, 4, 14, 1], width_multiplier=[1.5, 1.5, 1.5, 2.75], override_groups_map=None, **kwargs)def RepVGG_B0(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[1, 1, 1, 2.5], override_groups_map=None, **kwargs)def RepVGG_B1(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2, 2, 2, 4], override_groups_map=None, **kwargs)def RepVGG_B1g2(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2, 2, 2, 4], override_groups_map=g2_map, **kwargs)def RepVGG_B1g4(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2, 2, 2, 4], override_groups_map=g4_map, **kwargs)def RepVGG_B2(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=None, **kwargs)def RepVGG_B2g2(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=g2_map, **kwargs)def RepVGG_B2g4(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=g4_map, **kwargs)def RepVGG_B3(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[3, 3, 3, 5], override_groups_map=None, **kwargs)def RepVGG_B3g2(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[3, 3, 3, 5], override_groups_map=g2_map, **kwargs)def RepVGG_B3g4(**kwargs):    return RepVGG(num_blocks=[4, 6, 16, 1], width_multiplier=[3, 3, 3, 5], override_groups_map=g4_map, **kwargs)

   

模型配置

高层 API 通过 paddle.Model 类来配置模型In [4]

# 设置模型的输入和标签images = InputSpec(shape=[-1, 3, 32, 32], dtype='float32', name='images')labels = InputSpec(shape=[-1], dtype='int64', name='labels')# 初始化模型model = paddle.Model(RepVGG_A0(in_channels=3, class_dim=10), inputs=images, labels=labels)# 加载预训练模型参数model.load(path='data/data69662/RepVGG_A0', skip_mismatch=True, reset_optimizer=True)# 打印模型结构model.summary()# 配置优化器opt = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())# 配置模型model.prepare(optimizer=opt, loss=nn.CrossEntropyLoss(), metrics=paddle.metric.Accuracy(topk=(1, 5)))

       

/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py:1206: UserWarning: Skip loading for linear.weight. linear.weight receives a shape [1280, 1000], but the expected shape is [1280, 10].  ("Skip loading for {}. ".format(key) + str(err)))/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py:1206: UserWarning: Skip loading for linear.bias. linear.bias receives a shape [1000], but the expected shape is [10].  ("Skip loading for {}. ".format(key) + str(err)))/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model_summary.py:107: UserWarning: Your model was created in static mode, this may not get correct summary information!  "Your model was created in static mode, this may not get correct summary information!"/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/nn/layer/norm.py:636: UserWarning: When training, we now always track global mean and variance.  "When training, we now always track global mean and variance.")

       

-------------------------------------------------------------------------------   Layer (type)         Input Shape          Output Shape         Param #    ===============================================================================     Conv2D-1         [[1, 3, 32, 32]]     [1, 48, 16, 16]         1,296        BatchNorm2D-1     [[1, 48, 16, 16]]     [1, 48, 16, 16]          192           ConvBN-1         [[1, 3, 32, 32]]     [1, 48, 16, 16]         1,488          Conv2D-2         [[1, 3, 32, 32]]     [1, 48, 16, 16]          144         BatchNorm2D-2     [[1, 48, 16, 16]]     [1, 48, 16, 16]          192           ConvBN-2         [[1, 3, 32, 32]]     [1, 48, 16, 16]          336            ReLU-1         [[1, 48, 16, 16]]     [1, 48, 16, 16]           0          RepVGGBlock-1      [[1, 3, 32, 32]]     [1, 48, 16, 16]         1,824          Conv2D-3        [[1, 48, 16, 16]]      [1, 48, 8, 8]         20,736        BatchNorm2D-3      [[1, 48, 8, 8]]       [1, 48, 8, 8]           192           ConvBN-3        [[1, 48, 16, 16]]      [1, 48, 8, 8]         20,928          Conv2D-4        [[1, 48, 16, 16]]      [1, 48, 8, 8]          2,304        BatchNorm2D-4      [[1, 48, 8, 8]]       [1, 48, 8, 8]           192           ConvBN-4        [[1, 48, 16, 16]]      [1, 48, 8, 8]          2,496           ReLU-2          [[1, 48, 8, 8]]       [1, 48, 8, 8]            0          RepVGGBlock-2     [[1, 48, 16, 16]]      [1, 48, 8, 8]         23,424        BatchNorm2D-5      [[1, 48, 8, 8]]       [1, 48, 8, 8]           192           Conv2D-5         [[1, 48, 8, 8]]       [1, 48, 8, 8]         20,736        BatchNorm2D-6      [[1, 48, 8, 8]]       [1, 48, 8, 8]           192           ConvBN-5         [[1, 48, 8, 8]]       [1, 48, 8, 8]         20,928          Conv2D-6         [[1, 48, 8, 8]]       [1, 48, 8, 8]          2,304        BatchNorm2D-7      [[1, 48, 8, 8]]       [1, 48, 8, 8]           192           ConvBN-6         [[1, 48, 8, 8]]       [1, 48, 8, 8]          2,496           ReLU-3          [[1, 48, 8, 8]]       [1, 48, 8, 8]            0          RepVGGBlock-3      [[1, 48, 8, 8]]       [1, 48, 8, 8]         23,616          Conv2D-7         [[1, 48, 8, 8]]       [1, 96, 4, 4]         41,472        BatchNorm2D-8      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-7         [[1, 48, 8, 8]]       [1, 96, 4, 4]         41,856          Conv2D-8         [[1, 48, 8, 8]]       [1, 96, 4, 4]          4,608        BatchNorm2D-9      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-8         [[1, 48, 8, 8]]       [1, 96, 4, 4]          4,992           ReLU-4          [[1, 96, 4, 4]]       [1, 96, 4, 4]            0          RepVGGBlock-4      [[1, 48, 8, 8]]       [1, 96, 4, 4]         46,848       BatchNorm2D-10      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           Conv2D-9         [[1, 96, 4, 4]]       [1, 96, 4, 4]         82,944       BatchNorm2D-11      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-9         [[1, 96, 4, 4]]       [1, 96, 4, 4]         83,328          Conv2D-10        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,216       BatchNorm2D-12      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-10        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,600           ReLU-5          [[1, 96, 4, 4]]       [1, 96, 4, 4]            0          RepVGGBlock-5      [[1, 96, 4, 4]]       [1, 96, 4, 4]         93,312       BatchNorm2D-13      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           Conv2D-11        [[1, 96, 4, 4]]       [1, 96, 4, 4]         82,944       BatchNorm2D-14      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-11        [[1, 96, 4, 4]]       [1, 96, 4, 4]         83,328          Conv2D-12        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,216       BatchNorm2D-15      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-12        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,600           ReLU-6          [[1, 96, 4, 4]]       [1, 96, 4, 4]            0          RepVGGBlock-6      [[1, 96, 4, 4]]       [1, 96, 4, 4]         93,312       BatchNorm2D-16      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           Conv2D-13        [[1, 96, 4, 4]]       [1, 96, 4, 4]         82,944       BatchNorm2D-17      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-13        [[1, 96, 4, 4]]       [1, 96, 4, 4]         83,328          Conv2D-14        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,216       BatchNorm2D-18      [[1, 96, 4, 4]]       [1, 96, 4, 4]           384           ConvBN-14        [[1, 96, 4, 4]]       [1, 96, 4, 4]          9,600           ReLU-7          [[1, 96, 4, 4]]       [1, 96, 4, 4]            0          RepVGGBlock-7      [[1, 96, 4, 4]]       [1, 96, 4, 4]         93,312          Conv2D-15        [[1, 96, 4, 4]]       [1, 192, 2, 2]        165,888      BatchNorm2D-19      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-15        [[1, 96, 4, 4]]       [1, 192, 2, 2]        166,656         Conv2D-16        [[1, 96, 4, 4]]       [1, 192, 2, 2]        18,432       BatchNorm2D-20      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-16        [[1, 96, 4, 4]]       [1, 192, 2, 2]        19,200           ReLU-8          [[1, 192, 2, 2]]      [1, 192, 2, 2]           0          RepVGGBlock-8      [[1, 96, 4, 4]]       [1, 192, 2, 2]        185,856      BatchNorm2D-21      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-17        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-22      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-17        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-18        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-23      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-18        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-9          [[1, 192, 2, 2]]      [1, 192, 2, 2]           0          RepVGGBlock-9      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-24      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-19        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-25      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-19        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-20        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-26      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-20        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-10         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-10      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-27      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-21        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-28      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-21        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-22        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-29      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-22        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-11         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-11      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-30      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-23        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-31      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-23        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-24        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-32      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-24        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-12         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-12      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-33      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-25        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-34      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-25        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-26        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-35      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-26        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-13         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-13      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-36      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-27        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-37      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-27        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-28        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-38      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-28        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-14         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-14      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-39      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-29        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-40      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-29        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-30        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-41      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-30        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-15         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-15      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-42      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-31        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-43      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-31        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-32        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-44      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-32        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-16         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-16      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-45      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-33        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-46      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-33        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-34        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-47      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-34        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-17         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-17      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-48      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-35        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-49      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-35        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-36        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-50      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-36        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-18         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-18      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-51      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-37        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-52      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-37        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-38        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-53      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-38        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-19         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-19      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-54      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-39        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-55      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-39        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-40        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-56      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-40        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-20         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-20      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944      BatchNorm2D-57      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           Conv2D-41        [[1, 192, 2, 2]]      [1, 192, 2, 2]        331,776      BatchNorm2D-58      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-41        [[1, 192, 2, 2]]      [1, 192, 2, 2]        332,544         Conv2D-42        [[1, 192, 2, 2]]      [1, 192, 2, 2]        36,864       BatchNorm2D-59      [[1, 192, 2, 2]]      [1, 192, 2, 2]          768           ConvBN-42        [[1, 192, 2, 2]]      [1, 192, 2, 2]        37,632           ReLU-21         [[1, 192, 2, 2]]      [1, 192, 2, 2]           0         RepVGGBlock-21      [[1, 192, 2, 2]]      [1, 192, 2, 2]        370,944         Conv2D-43        [[1, 192, 2, 2]]     [1, 1280, 1, 1]       2,211,840     BatchNorm2D-60     [[1, 1280, 1, 1]]     [1, 1280, 1, 1]         5,120          ConvBN-43        [[1, 192, 2, 2]]     [1, 1280, 1, 1]       2,216,960        Conv2D-44        [[1, 192, 2, 2]]     [1, 1280, 1, 1]        245,760      BatchNorm2D-61     [[1, 1280, 1, 1]]     [1, 1280, 1, 1]         5,120          ConvBN-44        [[1, 192, 2, 2]]     [1, 1280, 1, 1]        250,880          ReLU-22        [[1, 1280, 1, 1]]     [1, 1280, 1, 1]           0         RepVGGBlock-22      [[1, 192, 2, 2]]     [1, 1280, 1, 1]       2,467,840   AdaptiveAvgPool2D-1  [[1, 1280, 1, 1]]     [1, 1280, 1, 1]           0            Linear-1           [[1, 1280]]            [1, 10]            12,810     ===============================================================================Total params: 23,556,330Trainable params: 23,509,034Non-trainable params: 47,296-------------------------------------------------------------------------------Input size (MB): 0.01Forward/backward pass size (MB): 2.38Params size (MB): 89.86Estimated Total Size (MB): 92.25-------------------------------------------------------------------------------

       

/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/layers/math_op_patch.py:298: UserWarning: :53The behavior of expression A + B has been unified with elementwise_add(X, Y, axis=-1) from Paddle 2.0. If your code works well in the older versions but crashes in this version, try to use elementwise_add(X, Y, axis=0) instead of A + B. This transitional warning will be dropped in the future.  op_type, op_type, EXPRESSION_MAP[method_name]))/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/layers/math_op_patch.py:298: UserWarning: /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/metric/metrics.py:270The behavior of expression A == B has been unified with equal(X, Y, axis=-1) from Paddle 2.0. If your code works well in the older versions but crashes in this version, try to use equal(X, Y, axis=0) instead of A == B. This transitional warning will be dropped in the future.  op_type, op_type, EXPRESSION_MAP[method_name]))

       

数据集配置

本次使用经典的 Cifar10 分类数据集进行演示本数据集已集成在 Paddle 中,可以直接通过 API 进行调用In [5]

# 配置数据预处理# 通道转置 + 归一化transform = Compose([Transpose(), Normalize(mean=127.5, std=127.5)])# 加载数据集train_dataset = Cifar10(mode='train', transform=transform)val_dataset = Cifar10(mode='test',  transform=transform)

       

Cache file /home/aistudio/.cache/paddle/dataset/cifar/cifar-10-python.tar.gz not found, downloading https://dataset.bj.bcebos.com/cifar/cifar-10-python.tar.gz Begin to downloadDownload finished

       

模型训练

通过 model.fit 接口进行模型训练还可以通过添加回调函数进行训练数据可视化等操作可视化训练数据样例如下图:

高层 API 实现 RepVGG 模型微调 - 创想鸟        

In [6]

# 配置 VisualDL 可视化回调函数# 训练启动后可通过右侧可视化查看训练数据vdl_callback = paddle.callbacks.VisualDL(log_dir='log')# 模型训练# train_data 训练数据# eval_data 测试数据# batch_size 数据批大小# epochs 训练轮次# eval_freq 评测间隔# log_freq log 间隔# save_dir 保存目录# verbose log 方式# drop_last 是否丢弃末尾数据# num_workers 读取线程# callbacks 回调函数model.fit(    train_data=train_dataset,     eval_data=val_dataset,     batch_size=256,     epochs=2,     eval_freq=1,     log_freq=20,     save_dir='save_models',     save_freq=1,     verbose=1,     drop_last=False,     shuffle=True,    num_workers=8,     callbacks=vdl_callback)

       

The loss value printed in the log is the current step, and the metric is the average value of previous step.Epoch 1/2

       

/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/layers/utils.py:77: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  return (isinstance(seq, collections.Sequence) and

       

step 196/196 [==============================] - loss: 1.0396 - acc_top1: 0.6414 - acc_top5: 0.9535 - 51ms/step         save checkpoint at /home/aistudio/save_models/0Eval begin...The loss value printed in the log is the current batch, and the metric is the average value of previous step.step 40/40 [==============================] - loss: 2.1800 - acc_top1: 0.4489 - acc_top5: 0.9243 - 34ms/step        Eval samples: 10000Epoch 2/2step 196/196 [==============================] - loss: 0.5899 - acc_top1: 0.7437 - acc_top5: 0.9820 - 48ms/step        save checkpoint at /home/aistudio/save_models/1Eval begin...The loss value printed in the log is the current batch, and the metric is the average value of previous step.step 40/40 [==============================] - loss: 2.4723 - acc_top1: 0.4512 - acc_top5: 0.9275 - 37ms/step        Eval samples: 10000save checkpoint at /home/aistudio/save_models/final

       

模型预测

通过 model.predict_batch 可单独对一张图片进行预测In [8]

# 标签列表classes = ['飞机', '汽车', '鸟', '猫', '鹿', '狗', '青蛙', '马', '船', '卡车']# 预测图像路径test_img_path = 'cat.jpg'# 显示预测图像display(Image(test_img_path))# 读取测试图像test_img = cv2.imread(test_img_path)# 数据预处理# 缩放 + 通道转置 + 归一化 + 新增维度test_img = cv2.resize(test_img, (32, 32))test_img = transform(test_img)test_img = test_img[np.newaxis, ...]# 模型预测result = model.predict_batch(test_img)# 结果后处理# 取置信度最大的标签下标 + 标签转换index = np.argmax(result)predict_label = classes[index]# 打印结果print('该图片的预测结果为:%s' % predict_label)

       


               

该图片的预测结果为:猫

       

以上就是高层 API 实现 RepVGG 模型微调的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/51124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
为什么我的163邮箱被冻结了_163邮箱冻结原因与解冻方法
上一篇 2025年11月8日 20:36:29
浅析VSCode中如何手动配置Git(图文教程)
下一篇 2025年11月8日 20:36:31

相关推荐

  • Guava Multimap:高效获取并打印指定键的所有关联值

    guava multimap是处理一键多值映射关系的强大工具。要获取特定键的所有关联值,应直接使用其提供的`multimap#get(k)`方法。该方法会返回一个包含所有匹配值的`collection`,即使键不存在,也会返回一个空集合而非`null`,从而简化了值检索和空值处理逻辑,是比手动迭代键…

    2026年9月21日
    000
  • 控制台命令(Console Command)开发

    控制台命令是程序员日常工作中不可或缺的工具,它提高了开发效率并帮助理解和控制程序运行。1) 通过简单的文本输入,完成复杂任务,如文件管理和系统监控。2) 控制台命令可用于快速调试、测试代码和自动化重复工作。3) 开发控制台命令时需注意安全性和兼容性问题。4) 控制台命令可实现有趣功能,如监控服务器资…

    2026年9月21日
    100
  • 链路追踪(OpenTelemetry/Jaeger)集成

    要将opentelemetry和jaeger集成到java应用中,需按以下步骤操作:1.配置jaeger exporter,2.初始化opentelemetry,3.创建并管理span。通过这种方式,你可以有效地追踪和分析微服务间的调用链路,提升系统性能。 在现代微服务架构中,链路追踪已经成为诊断和…

    2026年9月21日
    000
  • Maingear电脑黑屏问题如何修复?专业级主机BIOS设置方法详尽

    Maingear电脑黑屏问题通常由BIOS设置、硬件接触不良或显示输出配置引起。首先应尝试进入BIOS,检查并调整显卡输出模式为PCIe/PEG,确保未误设为集成显卡;排查PCIe插槽模式兼容性,必要时切换为Gen3或Auto;若启动异常,可尝试切换UEFI/Legacy模式或恢复BIOS默认设置(…

    2026年9月21日
    000
  • 实测!Sora 2长视频优势大,Vidu Q2细节处理更胜一筹

    近日,AI视频工具领域的竞争愈发激烈。OpenAI推出的Sora 2刚刚登顶美区App Store榜单,国产新秀Vidu Q2便携重磅升级版本强势入局,引发广泛关注。不少从事自媒体创作与影视剪辑的朋友都在思考:这两款AI视频生成器,究竟谁更胜一筹?出于好奇,我亲自上手实测了一番,发现两者之间的差异更…

    用户投稿 2026年9月21日
    000
  • Java Stream 高效分组计数并获取Top N元素

    本文深入探讨了如何利用java stream api对数据进行高效的分组计数,并从中提取出现频率最高的top n元素。文章首先介绍了一种简洁的基于全排序的实现方式,该方法适用于数据集较小或top n值接近总数的情况。随后,针对大数据量和小型top n场景下的性能瓶颈,文章详细阐述了如何通过自定义`c…

    2026年9月21日
    000
  • mysql安装后如何优化配置文件

    答案:优化MySQL配置需先定位配置文件,再根据硬件和业务调整内存、InnoDB、连接等核心参数。具体包括设置innodb_buffer_pool_size为物理内存50%~70%,合理配置日志参数与连接数,启用慢查询日志,并使用工具辅助调优,避免过度配置,确保稳定高效。 MySQL 安装后,优化配…

    2026年9月21日
    000
  • 自定义协议与主流框架(如ThinkPHP)结合

    在thinkphp中实现自定义协议可以通过中间件机制。具体步骤包括:1. 创建中间件类customprotocolmiddleware,解析和验证请求的json格式和字段。2. 在应用配置文件中添加该中间件,使所有请求经过处理。通过这种方式,可以满足特定业务需求并提升应用的灵活性和可扩展性。 在开发…

    2026年9月21日
    000
  • mac怎么阻止特定app访问网络_Mac阻止应用访问网络方法

    可通过系统防火墙、hosts文件、第三方工具或pf防火墙阻止应用联网。首先,macOS内置防火墙可阻断入站连接,需在“系统设置-网络-防火墙”中添加应用并启用阻止;其次,编辑/etc/hosts文件,将目标域名指向127.0.0.1可屏蔽其网络访问,需刷新DNS缓存生效;再者,使用Little Sn…

    2026年9月21日
    000
  • VSCode的括号匹配功能如何自定义?

    可通过 settings.json 自定义括号高亮的边框和背景色;2. 用 editor.matchBrackets 控制是否启用高亮;3. 启用 bracketPairColorization 可为嵌套括号着色;4. 使用 Ctrl/Cmd + Shift + 快速跳转配对括号。 VSCode 的…

    2026年9月21日
    000
  • 马斯克xAI的Grok将推AI视频检测工具,能否破解深度伪造难题?

    随着ai视频生成技术飞速渗透网络,深度伪造内容不断扩散,网络信息真实性面临前所未有的挑战。在此背景下,马斯克的xai公司的grok模型即将推出一项关键升级,打造一款“真伪侦探”工具。 近日,马斯克在X平台回应网友担忧时表示,Grok即将获得识别AI生成视频并追踪其网络来源的能力,以此应对深度伪造内容…

    2026年9月21日
    000
  • AI推文助手如何生成节日祝福 AI推文助手的情感连接内容创作

    AI推文助手如何生成节日祝福 AI推文助手的情感连接内容创作AI推文助手如何生成节日祝福 AI推文助手的情感连接内容创作AI推文助手如何生成节日祝福 AI推文助手的情感连接内容创作AI推文助手如何生成节日祝福 AI推文助手的情感连接内容创作

    答案:通过AI推文助手的节日模板、情感关键词、用户数据定制和多语言混合策略,可高效生成个性化祝福,增强受众情感连接。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜ 如果您希望借助AI推文助手在节日期间传递温暖的祝福,同时增强与受众的情感连接…

    2026年9月21日 用户投稿
    000
  • 如何通过命令行参数启动VSCode?

    掌握VSCode命令行用法可提升开发效率,需先安装code命令到PATH,之后可用code .打开目录、code 文件名打开文件、code –diff比较文件、–disable-extensions排查问题,并支持别名与Shell结合使用。 通过命令行启动 VSCode 是一…

    2026年9月21日
    100
  • 如何基于Swoole开发自定义框架?

    基于swoole开发自定义框架可以通过以下步骤实现:1. 创建核心app类,初始化swoole服务器并定义回调函数;2. 实现路由功能,使用router类处理请求分发;3. 添加中间件支持,使用middleware类处理请求;4. 集成异步数据库操作,使用swoole的mysql协程客户端;5. 实…

    2026年9月21日
    000
  • 万人同时在线抽奖活动架构

    万人同时在线抽奖活动的系统架构应采用微服务架构、分布式数据库、redis缓存、区块链存储结果,并使用负载均衡和异步处理技术。具体包括:1.采用微服务架构和分布式数据库(如tidb)保证系统稳定性和可扩展性;2.使用redis处理抽奖逻辑,确保高效和随机性;3.将结果存入区块链,保证透明度和可验证性;…

    2026年9月21日
    000
  • 小可AI小程序入口链接_小可AI小程序官方地址

    小可AI小程序官方入口为https://xcx.xiaokeai.com.cn,用户可在社交平台搜索使用;平台支持多轮对话、文本生成、图像理解及语音转文字功能,界面简洁、响应迅速,具备历史记录查看与持续优化的智能算法。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepS…

    2026年9月21日
    000
  • Linux文件和目录管理常见命令

    Linux文件和目录管理依赖于ls、cd、mkdir、rm、cp、mv等核心命令,用于浏览、创建、删除、复制和移动文件与目录;通过find、du、grep等命令可查找文件、定位大文件并清理磁盘空间;使用rename、mmv或脚本可实现批量重命名;为安全起见,应谨慎使用rm命令,推荐结合-i选项或使用…

    2026年9月21日
    000
  • 大数据量下的批量导入/导出优化

    在大数据环境下优化批量导入/导出的方法包括:1. 使用批处理技术分批导入/导出数据,减少系统资源压力;2. 采用数据流技术如apache kafka进行实时处理,降低内存占用;3. 利用并行处理技术分配任务到多个处理器或节点,提高处理速度;4. 通过性能监控和调优识别并解决瓶颈点,以提升整体效率。 …

    2026年9月21日
    200
  • 《忍者龙剑传4》明日发售 制作人谈亮点:经典与创新并存!

    白金工作室今日迎来《忍者龙剑传4》(ninja gaiden 4)制作人兼导演中尾裕治的特别公告,正式确认游戏将于10月21日(周二)全球上线。中尾在声明中详细介绍了本作的核心特色,强调在传承系列精髓的同时注入全新机制,为玩家打造既怀旧又充满惊喜的忍者冒险。 特色一:传承与进化的战斗系统 系列经典操…

    2026年9月21日
    000
  • mysqlmysql如何优化in条件大列表查询

    使用EXPLAIN和慢查询日志判断IN性能问题,type为ALL且possible_keys为空或rows过大说明需优化;JOIN在有索引时通常优于IN,尤其当列表值来自另一表时;大IN列表可拆分为多个小IN结合UNION ALL,或存入临时表后用JOIN提升效率。 优化 MySQL 中 IN 条件…

    2026年9月21日
    000

发表回复

登录后才能评论
关注微信