可变形卷积link
class DCNv2(nn.Module):def __init__(self, in_channels, out_channels, kernel_size, stride=1,padding=1, groups=1, act=True, dilation=1, deformable_groups=1):super(DCNv2, self).__init__()self.in_channels = in_channelsself.out_channels = out_channelsself.kernel_size = (kernel_size, kernel_size)self.stride = (stride, stride)self.padding = (autopad(kernel_size, padding), autopad(kernel_size, padding))self.dilation = (dilation, dilation)self.groups = groupsself.deformable_groups = deformable_groupsself.weight = nn.Parameter(torch.empty(out_channels, in_channels, *self.kernel_size))self.bias = nn.Parameter(torch.empty(out_channels))out_channels_offset_mask = (self.deformable_groups * 3 *self.kernel_size[0] * self.kernel_size[1])self.conv_offset_mask = nn.Conv2d(self.in_channels,out_channels_offset_mask,kernel_size=self.kernel_size,stride=self.stride,padding=self.padding,bias=True,)self.bn = nn.BatchNorm2d(out_channels)self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())self.reset_parameters()def forward(self, x):offset_mask = self.conv_offset_mask(x)o1, o2, mask = torch.chunk(offset_mask, 3, dim=1)offset = torch.cat((o1, o2), dim=1)mask = torch.sigmoid(mask)x = torch.ops.torchvision.deform_conv2d(x,self.weight,offset,mask,self.bias,self.stride[0], self.stride[1],self.padding[0], self.padding[1],self.dilation[0], self.dilation[1],self.groups,self.deformable_groups,True)x = self.bn(x)x = self.act(x)return xdef reset_parameters(self):n = self.in_channelsfor k in self.kernel_size:n *= kstd = 1. / math.sqrt(n)self.weight.data.uniform_(-std, std)self.bias.data.zero_()self.conv_offset_mask.weight.data.zero_()self.conv_offset_mask.bias.data.zero_()
1、复制到common.py文件下面
2、yolo.py文件,引入
3、yolo.yaml文件下修改
4、只需要改卷积核为3的卷积就可以了,为1的话就没必要改了,
5、一般可变形卷积是添加到主干网上,如果想添加到head部分,自行尝试。