深度学习模型预测时间很慢

您所在的位置:网站首页 训练神经网络需要多久 深度学习模型预测时间很慢

深度学习模型预测时间很慢

2023-08-13 00:19| 来源: 网络整理| 查看: 265

在做深度学习任务时,我是做图像目标检测,用tensorflow或者keras或者pytorch训练完模型,然后就是做预测,发现无论是用GPU还是CPU都非常慢,然后百度了好久都没有解决问题。

无论是不是配置低,如果我们要做成品,一定要部署。

我每个函数都去用time.time()去计算耗时,最后发现调用模型的时候耗时最多,也是罪魁祸首。 在这里插入图片描述

无论你是调用ssd或者yolo模型,在这里的调用都非常耗时。系统有初始化,每次你去预测一张图片,系统都要重新调用一次模型,初始化一次模型,加载一次模型,这样就很慢了,我们的思路应该是这样,模型一直在系统后台跑着,初始化着,然后直接去用模型去预测就快了。

我是用了flask去做接口然后调用模型的。查了资料,flask对轻量级不错,也是主流的框架。

下面示范flask调用yolo目标检测的代码:

1.创建一个 API.py:

from flask import Flask,request,make_response from PIL import Image from io import BytesIO from yolo import YOLO import json app = Flask(__name__) # 加载模型 yolo = YOLO() # 处理请求 @app.route('/yolo', methods=['POST']) def hello(): global yolo img = request.stream.read() f = BytesIO(img) image = Image.open(f) out_boxes, out_scores, out_classes = yolo.detect_image2(image) data = [] for i, c in reversed(list(enumerate(out_classes))): item = { 'predicted_class': yolo.class_names[c], #'box': out_boxes[i], 'score': str(out_scores[i]) } data.append(item) rsp = make_response(json.dumps(data)) rsp.mimetype = 'application/json' rsp.headers['Connection'] = 'close' return rsp if __name__ == '__main__': #app.debug = True app.run(processes=1,threaded=False)

yolo启动时初始化,常驻内存,这样识别速度就提高很多

2.在你自己工程的 yolo.py加上这个函数:

def detect_image2(self, image): if self.model_image_size != (None, None): assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required' assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required' boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) else: new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32)) boxed_image = letterbox_image(image, new_image_size) image_data = np.array(boxed_image, dtype='float32') image_data /= 255. image_data = np.expand_dims(image_data, 0) # Add batch dimension. out_boxes, out_scores, out_classes = self.sess.run( [self.boxes, self.scores, self.classes], feed_dict={ self.yolo_model.input: image_data, self.input_image_shape: [image.size[1], image.size[0]], K.learning_phase(): 0 }) return out_boxes, out_scores, out_classes

3.用Python写一个调用API接口的 test.py:(这里也可以用其他语言去调用我们的API)

import requests import os import json url = 'http://127.0.0.1:5000/yolo' headers = {'Content-Type' : 'image/jpeg'} files = {'media': open('1.jpg', 'rb')}#你要预测的图片 requests.post(url, files=files) data = open('1.jpg','rb').read() r = requests.post(url,data=data, headers=headers, verify=False) print(r.text)

1.jpg就是你要预测的图片

其他模型或者调用视频大家举一反三就好了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3