目录
1.2 在common.py后面加入如下刚刚定义的网络,就是上面的代码的一部分
2. 如此修改网络的yaml文件,yolov5n_res18.yaml
1.网络结构
残差18网络如下
可做出如下修改
1.1 三层如下定义
import torch
from torch import nn
from torchvision import models
from torchinfo import summary
class resnet18(nn.Module):
def __init__(self,n):
super().__init__()
model = models.resnet18(pretrained=True)
if n==1:
layer=[]
layer+=[model.conv1]
layer+=[model.bn1]
layer+=[model.relu]
layer+=[model.maxpool]
layer+=[model.layer1]
layer+=[model.layer2]
self.model=nn.Sequential(*layer)
if n==2:
self.model=model.layer3
if n==3:
self.model=model.layer4
def forward(self, x):
return self.model(x)
if __name__ == '__main__':
x=torch.randn(1,3,640,640)#torch.Size([1, 128, 80, 80])
x=torch.randn(1, 128, 80, 80)#torch.Size([1, 256, 40, 40]
x=torch.randn(1, 256, 40, 40)#torch.Size([1, 512, 20, 20])
net=resnet18(3)#
out=net(x)
print(out.shape)
# summary(net,(1,3,640,640))
1.2 在common.py后面加入如下刚刚定义的网络,就是上面的代码的一部分
2. 如此修改网络的yaml文件,yolov5n_res18.yaml
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Parameters
nc: 80 # number of classes
depth_multiple: 0.33 # model depth multiple
width_multiple: 0.25 # layer channel multiple
anchors:
- [ 10,13, 16,30, 33,23 ] # P3/8
- [ 30,61, 62,45, 59,119 ] # P4/16
- [ 116,90, 156,198, 373,326 ] # P5/32
# YOLOv5 v6.0 backbone
backbone:
# [from, number, module, args]
[ [ -1, 1, resnet18, [ 128, 1 ] ], # 0-P1/2
[ -1, 1, resnet18, [ 256,2 ] ], # 1-P2/4
[ -1, 1, resnet18, [ 512,3 ] ],
]
# YOLOv5 v6.0 head
head:
[ [ -1, 1, Conv, [ 512, 1, 1 ] ],
[ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
[ [ -1, 1 ], 1, Concat, [ 1 ] ], # cat backbone P4
[ -1, 3, C3, [ 512, False ] ], # 13
[ -1, 1, Conv, [ 256, 1, 1 ] ],
[ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
[ [ -1, 0 ], 1, Concat, [ 1 ] ], # cat backbone P3
[ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
[ -1, 1, Conv, [ 256, 3, 2 ] ],
[ [ -1, 7 ], 1, Concat, [ 1 ] ], # cat head P4
[ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium)
[ -1, 1, Conv, [ 512, 3, 2 ] ],
[ [ -1, 3 ], 1, Concat, [ 1 ] ], # cat head P5
[ -1, 3, C3, [ 1024, False ] ], # 23 (P5/32-large)
[ [ 10, 13, 16 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5)
]
3. 修改yolo网络并运行
需要导包的可以自己导一下
更换网络后run一下yolo.py的参数如下