在此教程中跟着博主一步一步进行项目复现时出现了一些代码运行时的报错,查阅网上的解决方法后做一个集合。
问题一
在运行train.py时报错如下:
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘E:\yolov5-5.0\models\
解决方法:
在项目的models目录下找到common.py把SPPF这个类加进去(记得引入warnings这个包),代码如下:
import warnings
class SPPF(nn.Module):
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * 4, c2, 1, 1)
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
y1 = self.m(x)
y2 = self.m(y1)
return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
问题二
在运行train.py训练过程中报错如下:
RuntimeError: result type Float can‘t be cast to the desired output type __int64RuntimeError: result type Float can‘t be cast to the desired output type __int64
解决方法:
在项目的utils目录下找到loss.py将末尾的for函数进行替换,替换版本为yolov5-master版本。
代码如下:
for i in range(self.nl):
anchors, shape = self.anchors[i], p[i].shape
gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
# Match targets to anchors
t = targets * gain # shape(3,n,7)
if nt:
# Matches
r = t[..., 4:6] / anchors[:, None] # wh ratio
j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
t = t[j] # filter
# Offsets
gxy = t[:, 2:4] # grid xy
gxi = gain[[2, 3]] - gxy # inverse
j, k = ((gxy % 1 < g) & (gxy > 1)).T
l, m = ((gxi % 1 < g) & (gxi > 1)).T
j = torch.stack((torch.ones_like(j), j, k, l, m))
t = t.repeat((5, 1, 1))[j]
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
else:
t = targets[0]
offsets = 0
# Define
bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
gij = (gxy - offsets).long()
gi, gj = gij.T # grid indices
# Append
indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
anch.append(anchors[a]) # anchors
tcls.append(c) # class
问题三
训练完成后,运行detect.py进行推理时,出现如下报错:
AttributeError: ‘Upsample‘ object has no attribute ‘recompute_scale_factor’
解决方法:
根据光标定位报错的位置,找到自定义函数def forward(self, input: Tensor) -> Tensor进行替换,
代码如下:
def forward(self, input: Tensor) -> Tensor:
return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners)
问题四
想通过调用电脑自带摄像头,运行detect.py进行推理时,报错如下:
TypeError: argument of type ' int ' is not iterable
解决方法:
在项目的utils目录下找到datasets.py,在文件的第279行给两个url参数进行类型转换,
将两个url变成str(url)。