在探究yolov5源代码中 process match部分,matches代码段的时候调试遇到了一下问题。
ValueError Traceback (most recent call last)
<ipython-input-40-9452df23b94c> in <module>
15 print(matches)
16 matchesn = matches.numpy()
---> 17 matches2 = matches[:, 2].argsort()[::-1]
18 matchesn2 = matchesn[:, 2].argsort()[::-1]
19 print(matches2)
ValueError: step must be greater than zero
经对比分析,这是由于pytorch和numpy中,argsort()函数均有定义,但是对tensor形式变量和numpy形式变量的具体使用方法不同。当变量a为一维numpy数组的时候,a.argsort()[::-1]能够正确用数组切片的形式([start : end : step]),实现一维数组a全部元素的倒序排列。当变量a为一维tensor的时候,上述方法失效并报错“step must be greater than zero”。
yolov5 在此处是将tensor转换为了numpy之后进行倒序实现,从tensor直接实现需要以下代码。
import torch
a = torch.tensor([1,5,2,6,7])
a,a_index = a.sort(descending = True)
b,b_index = a.sort()
a[a_index] = a