YOLOV5 代码学习总结
- 摘要 在学习YOLOV5代码过程中记录一些代码理解
计算AP值 compute_ap
def compute_ap(recall, precision):
""" Compute the average precision, given the recall and precision curves.
Source: https://github.com/rbgirshick/py-faster-rcnn.
# Arguments
recall: The recall curve (list).
precision: The precision curve (list).
# Returns
The average precision as computed in py-faster-rcnn.
"""
# Append sentinel values to beginning and end
mrec = recall # np.concatenate(([0.], recall, [recall[-1] + 1E-3]))
mpre = precision # np.concatenate(([0.], precision, [0.]))
# Compute the precision envelope
mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
# Integrate area under curve
method = 'interp' # methods: 'continuous', 'interp'
if method == 'interp':
x = np.linspace(0, 1, 101) # 101-point interp (COCO)
ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
else: # 'continuous'
i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
return ap, mpre, mrec
- np.maximum.accumulate()
计算数组(或数组的特定轴)的累积最大值:
例如:d = np.array([2, 0, 3, -4, -2, 7, 9])
c = np.maximum.accumulate(d) # array([2, 2, 3, 3, 3, 7, 9])
- np.flip()
[参考连接](https://numpy.org/doc/stable/reference/generated/numpy.flip.html)
A = np.arange(8).reshape((2,2,2))
A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
np.flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
np.flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
np.flip(A)
array([[[7, 6],
[5, 4]],
[[3, 2],
[1, 0]]])
np.flip(A, (0, 2))
array([[[5, 4],
[7, 6]],
[[1, 0],
[3, 2]]])
- np.interp(x, xp, fp, left=None, right=None, period=None)
参考链接
一维线性插值返回离散数据的一维分段线性插值结果.
参数
x: 数组
待插入数据的横坐标.
xp: 一维浮点数序列
原始数据点的横坐标,如果period参数没有指定那么就必须是递增的。否则,在使用xp = xp % period正则化之后,xp在内部进行排序.
fp: 一维浮点数或复数序列
原始数据点的纵坐标,和xp序列等长.
left: 可选参数,类型为浮点数或复数(对应于fp值),当x < xp[0]时的插值返回值,默认为fp[0].
right: 可选参数,类型为浮点数或复数(对应于fp值),当x > xp[-1]时的插值返回值,默认为fp[-1].
period: None或者浮点数,可选参数. 横坐标的周期. 此参数使得可以正确插入angular x-coordinates. 如果该参数被设定,那么忽略left参数和right参数。
返回值
浮点数或复数(对应于fp值)或ndarray. 插入数据的纵坐标,和x形状相同。
x = [0, 1, 1.5, 2.72, 3.14]
xp = [1, 2, 3]
fp = [3, 2, 0]
y = np.interp(x, xp, fp) # array([ 3. , 3. , 2.5 , 0.56, 0. ])
plt.plot(xp, fp, '-o')
plt.plot(x, y, 'x')
plt.show()
当对应的x序列为[0, 1, 1.5, 2.72, 3.14]时,得到的y序列是[ 3. , 3. , 2.5 , 0.56, 0. ],需要注意的是当x=0时,由于0 < xp[0],所以y被设定为fp[0],也就是3,当x=3.14时,由于3.14 > xp[-1],则y被设定为fp[-1],也就是0。
- np.trapz(np.interp(x, mrec, mpre), x)
参考链接
这里np.interp(x, mrec, mpre)和x长度一致,计算两者围成的面积。
np.trapz([1,2,3])
4.0
np.trapz([1,2,3], x=[4,6,8])
8.0
np.trapz([1,2,3], dx=2)
8.0
theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
np.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841