加速理解Python Keras预测方法结果分析

Speeding up and understanding Python Keras predict method results analysis

我正在使用 Keras 和 Tensorflow 使用 Yolov3 标准和 Yolov3-Tiny(大约快 10 倍)执行对象检测。一切正常,但性能相当差,我在 GPU 上每 2 秒获得一帧,在 CPU 上每 4 秒左右获得一帧。在分析代码时,发现 decode_netout 方法花费了大量时间。我通常以 this tutorial 为例。

  1. 有人可以帮助我了解它在做什么吗?
  2. Tensorflow(或其他库)中是否有替代方法可以进行这些计算?例如,我将一些自定义 Python 换成 tf.image.non_max_suppression,它在性能方面帮助很大。
# https://keras.io/models/model/
yhat = model.predict(image, verbose=0, use_multiprocessing=True)
# define the probability threshold for detected objects
class_threshold = 0.6
boxes = list()
for i in range(len(yhat)):
    # decode the output of the network
    boxes += detect.decode_netout(yhat[i][0], anchors[i], class_threshold, input_h, input_w)
def decode_netout(netout, anchors, obj_thresh, net_h, net_w):
    grid_h, grid_w = netout.shape[:2]
    nb_box = 3
    netout = netout.reshape((grid_h, grid_w, nb_box, -1))
    boxes = []
    netout[..., :2]  = _sigmoid(netout[..., :2])
    netout[..., 4:]  = _sigmoid(netout[..., 4:])
    netout[..., 5:]  = netout[..., 4][..., np.newaxis] * netout[..., 5:]
    netout[..., 5:] *= netout[..., 5:] > obj_thresh

    for i in range(grid_h*grid_w):
        row = i / grid_w
        col = i % grid_w
        for b in range(nb_box):
            # 4th element is objectness score
            objectness = netout[int(row)][int(col)][b][4]
            if(objectness.all() <= obj_thresh): continue
            # first 4 elements are x, y, w, and h
            x, y, w, h = netout[int(row)][int(col)][b][:4]
            x = (col + x) / grid_w # center position, unit: image width
            y = (row + y) / grid_h # center position, unit: image height
            w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width
            h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height
            # last elements are class probabilities
            classes = netout[int(row)][col][b][5:]
            box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes)
            boxes.append(box)
    return boxes

我有一个类似的 GPU 设置,并且一直面临同样的问题。我一直在从事 YoloV3 Keras 项目,过去 2 周一直在追查确切的问题。在最终对我所有的功能进行时间​​限制后,我发现将问题缩小到 'def do_nms',然后将我带到您在 'def decode_netout' 上面发布的功能。问题是非最大抑制很慢。

我找到的解决方案是调整这条线

if(objectness.all() <= obj_thresh): continue

if (objectness <= obj_thresh).all(): continue

性能差异是白天和黑夜。我正在推动接近 30 FPS 并且一切都运行得更好。

归功于此 Git issue/solution:

https://github.com/experiencor/keras-yolo3/issues/177

我花了一段时间才弄明白,所以我希望这对其他人有帮助。