sess.run() слишком медленный
Функция sess.run() модуля обнаружения объектов Tensorflow занимает около 2,5 секунд, чтобы обнаружить ограничивающие кадры на изображении 600x600. Как я могу ускорить этот код?
def run(image, detection_graph):
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# Definite input and output Tensors for detection_graph
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = image
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
print("2")
start_time = datetime.datetime.now()
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
end_time = datetime.datetime.now()
diff = (end_time - start_time).total_seconds()*1000
print (diff)
print("3")
return boxes[0], scores[0]
#print scores
#print classes
1 ответ
Ваш sess.run
время выполнения является нормальным для первого запуска, после этого он, вероятно, будет работать в 100 раз быстрее (не шучу).
Ключом является повторное использование сеанса, в вашем примере я бы добавил еще одну оценку изображения, измерил бы это время и проверил, улучшается ли производительность, например:
# all your prev code here
print (diff)
print("3")
image_np = image2 # get another image from somewhere
image_np_expanded = np.expand_dims(image_np, axis=0)
start_time = datetime.datetime.now()
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
end_time = datetime.datetime.now()
diff = (end_time - start_time).total_seconds()*1000
print("Detection #2")
print(diff)
Таким образом, вам не нужны графические процессоры или меньшие изображения (пока), просто "прогрейте" сеанс и используйте его для всех прогнозов.
В настоящее время у меня очень скромная установка в тестовой среде с последней версией Ubuntu, работающей на VirtualBox, одноядерной и без графического процессора (набор данных MobileNet2 + COCO), время, которое я получаю, довольно приличное, когда сессия "теплая".
--- 3.7862255573272705 seconds ---
--- 0.21631121635437012 seconds ---
--- 0.1784508228302002 seconds ---
Обратите внимание на первое медленное время выполнения, последним было изображение размером 1050*600