yolov5在运行之前会先用全0的数据跑一遍,确保我们的网络配置能够跑通,但是源码设置的全0数据的shape为[1,3,256,256],batch size为1,这就导致了我们的有些Batch Normalization操作会出现以下报错:
Expected more than 1 value per channel when training, got input size torch.Size([1, *])
因为batch size==1是不能进行BN操作的,所以我们需要修改源码给的全零数据的shape,首先在yolo.py文件的Model类下,将下面的torch.zeros(1, ch, s, s)改为torch.zeros(2, ch, s, s)。
# Build strides, anchors
m = self.model[-1] # Detect()
if isinstance(m, Detect):
s = 256 # 2x min stride
m.inplace = self.inplace
# 这边可以修改运行yolo.py时生成的默认batch_size,channel,height和weight
# m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(2, ch, s, s))]) # forward