尽管yolov7模型整体的性能优于yolov5, 不过yolov7-tiny到yolov7之间的跨度比较大(可以通过剪枝yolov7来得到中间模型,这个后面再讲),这个中间的跨度我们可以用yolov5s来补充,整体上yolov5项目和yolov7项目的使用方式基本上一模一样,那么我们能不能把这两个合到一个项目里呢,免得要维护2个项目。此外,yolov7加入了OTA loss,性能要略好于yolov5的loss, 如果我们把yolov5加入yolov7, 就可以直接用上了,而不用去修改yolov5项目。
yolov5和yolov7模式基本一样,都是通过yaml文件来控制模型结构,所以首先我们要将yolov5的模型yaml文件拷贝到yolov7项目,以yolov5s为例,拷贝yolov5/models/yolov5s.yaml到yolov7/cfg/training
yolov5中的C3模块默认不在yolov7项目中,我们需要将其定义添加到yolov7中:
从yolov5/models/common.py中拷贝C3的定义:
class C3(nn.Module):
# CSP Bottleneck with 3 convolutions
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
def forward(self, x):
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
到yolov7/models/common.py中,可以将其添加到其中的#### yolov5 ####下。
修改yolov7的yolo.py文件,具体而言是修改parse_model
,从而在解析yaml文件时,能够正确解析, 将C3加入到下面的列表中,:
if m in [nn.Conv2d, Conv, RobustConv, RobustConv2, DWConv, GhostConv, RepConv, RepConv_OREPA, DownC,
SPP, SPPF, SPPCSPC, GhostSPPCSPC, MixConv2d, Focus, Stem, GhostStem, CrossConv,
Bottleneck, BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
RepBottleneck, RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
Res, ResCSPA, ResCSPB, ResCSPC,
RepRes, RepResCSPA, RepResCSPB, RepResCSPC,
ResX, ResXCSPA, ResXCSPB, ResXCSPC,
RepResX, RepResXCSPA, RepResXCSPB, RepResXCSPC,
Ghost, GhostCSPA, GhostCSPB, GhostCSPC,
SwinTransformerBlock, STCSPA, STCSPB, STCSPC,
SwinTransformer2Block, ST2CSPA, ST2CSPB, ST2CSPC,C3]:
c1, c2 = ch[f], args[0]
if c2 != no: # if not output
c2 = make_divisible(c2 * gw, 8)
args = [c1, c2, *args[1:]]
if m in [DownC, SPPCSPC, GhostSPPCSPC,
BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
ResCSPA, ResCSPB, ResCSPC,
RepResCSPA, RepResCSPB, RepResCSPC,
ResXCSPA, ResXCSPB, ResXCSPC,
RepResXCSPA, RepResXCSPB, RepResXCSPC,
GhostCSPA, GhostCSPB, GhostCSPC,
STCSPA, STCSPB, STCSPC,
ST2CSPA, ST2CSPB, ST2CSPC,C3]:
args.insert(2, n) # number of repeats
n = 1
通过上述的修改,我们就可以像训练yolov7一样在yolov7项目中训练yolov5了,yolov5也能使用上yolov7的loss了。