
按照训练流程首先介绍backbone以及数据进入encoder之前的部分
当训练时,使用torch.manual_seed(seed)函数,只要网络参数不变的情况下,网络的参数初始化每次都是固定的;如果没有设置,每次训练时的初始化都是随机的,导致结果不确定。
例如:要训练自己的数据集通常需要对num_classes进行设置。(其中num_classes的设置根据自己数据集类别数量+1,也就是说,假设coco的数据集中总共有90个类,此时的num_classes就是91)
假设刚开始设置的num_classes=5,那么只要训练过程中网络的参数不变,那么网络的初始化参数都是一样的;如果下次训练时num_classes=6,最直观的变化就是数据集中图像的读取顺序发生了变化,并且由于训练时有对图像进行随机拉伸,也就导致参数变化后,同一张图像在上一次训练时的尺寸和当前训练尺寸不一。
backbone调用的是torchvision中定义的resnet50,这里的backbone也就是送入transformer之前用来提取图像特征图的骨架,所以张量在经过resnet50的卷积后得到的特征图通道数由原来的3通道变为2048,W*H = W/32 * H/32,具体来说,假设一开始输入的张量是由batch size为2,长宽都为768组成的3通道图像,即[b, c, h, w] = [2,3,768,768],经过resnet50后,shape变为[2,2048,24,24]。
具体的代码如下:
class ResNet(nn.Module):
def __init__(
self,
block: Type[Union[BasicBlock, Bottleneck]],
layers: List[int],
num_classes: int = 1000,
zero_init_residual: bool = False,
groups: int = 1,
width_per_group: int = 64,
replace_stride_with_dilation: Optional[List[bool]] = None,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.groups = groups
self.base_width = width_per_group
# 输入的W * H = W / 2 * H / 2
# 特征图分辨率降低为1/2,通道数从3升为64
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
# W * H = W / 2 * H / 2
# 特征图分辨率降低为1/4,通道数仍然为64
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# stride为1,不改变分辨率,依然为1/4,通道数从64升为256
self.layer1 = self._make_layer(block, 64, layers[0])
# W * H = W / 2 * H / 2
# stride为2,特征图分辨率降低为1/8,通道数从256升为512
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
# W * H = W / 2 * H / 2
# stride为2,特征图分辨率降低为1/16,通道数从512升为1024
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
# W * H = W / 2 * H / 2
# stride为2,特征图分辨率降低为1/32,通道数从512升为2048
self.layer4 = self._make_layer(block,

1万+

被折叠的 条评论
为什么被折叠?



