numpy.maximum和 numpy.argmax的使用小記

一.numpy.maximum

作用:

           按元素比較兩個列表,返回包含最大值的列表。

參數:x1,x2 是兩個待比較的列表。如果x1.shape!=x2.shape 則進行廣播操作然後再比較。

例子:

np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])

np.maximum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 1. ,  2. ],
       [ 0.5,  2. ]])

IOU計算中的列子:

boxes = np.array([[3,5],[2,7],[4,8]]).reshape(3,1,2)
anchors = np.array([[2,6],[1,8],[2,9],[3,10],[4,11],[4,9],[1,11],[2,19],[7,10]]).reshape(1,9,2)
#print(box1)
#print(box2)

class Iou_Same():
    def __init__(self,anchors,boxes):
        self.anchor_max = anchors//2
        self.anchor_min = -self.anchor_max
        self.box_max = boxes//2
        self.box_min = -self.box_max
        self.anchor_areas = anchors[...,0]*anchors[...,1]
        self.box_areas = boxes[...,0]*boxes[...,1]

    def cal_Iou(self):
        inter_max = np.minimum(self.anchor_max,self.box_max)
        inter_min = np.maximum(self.anchor_min,self.box_min)
        print(inter_max.shape)
        print(inter_min.shape)
        inter_wh = np.maximum(inter_max-inter_min,0.0)
        inter_areas = inter_wh[...,0]*inter_wh[...,1]
        union_areas = self.anchor_areas+self.box_areas-inter_areas
        iou_area = inter_areas/union_areas

        return iou_area
iou = Iou_Same(anchors,boxes)
iou_areas = iou.cal_Iou()
print(iou_areas.shape)
'''
print輸出:
(3, 9, 2)
(3, 9, 2)
(3, 9)

'''

這裏巧妙的運用了maximum廣播的效果,產生了3個box分別與9個anchor的交併比

二.numpy.argmax

numpy.argmax(aaxis=Noneout=None)

a:輸入的數組

axis:按那個維度進行(如果沒指定維度,則按照一維的形狀返回索引)

out:是個列表。如果傳入,最後輸出的結果將插入這個列表

返回的是一個索引列表,它和a.shape維度相同,但是axis軸的維度被刪除

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])   

#上面可以看出axis的維度已經沒有了
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b)  # 如果一個列表中有多個相同的最大值,只有第一個被返回
1
# np.unravel_index可以轉換索引到元組
>>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
>>> ind
(1, 2)
>>> a[ind]
15

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章