flask部署pytorch模型
项目代码:
https://pan.baidu.com/s/1-FdTk7XjryvUsZR9CW9T3g
提取码:6uo5
该项目上传至阿里云仓库:docker——构建自己的项目(阿里云仓库)| docker构建仓库镜像教程
目录
- 开启模型服务
- 调用模型(响应)
开启模型服务
run_pytorch_server.py
import io
import json
import flask
import torch
import torch
import torch.nn.functional as F
from PIL import Image
from torch import nn
from torchvision import transforms as T
from torchvision.models import resnet50
from torch.autograd import Variable # 初始化Flask app
app = flask.Flask(__name__)
model = None
use_gpu = False# 返回结果用的
with open('imagenet_class.txt', 'r') as f:idx2label = eval(f.read())# 加载模型进来
def load_model():"""Load the pre-trained model, you can use your model just as easily."""global model#这里我们直接加载官方工具包里提供的训练好的模型(代码会自动下载)括号内参数为是否下载模型对应的配置信息model = resnet50(pretrained=True)#将模型指定为测试格式model.eval()#是否使用gpuif use_gpu:model.cuda()# 数据预处理
def prepare_image(image, target_size):"""Do image preprocessing before prediction on any data.:param image: original image:param target_size: target image size:return:preprocessed image"""#针对不同模型,image的格式不同,但需要统一至RGB格式if image.mode != 'RGB':image = image.convert("RGB")# Resize the input image and preprocess it.(按照所使用的模型将输入图片的尺寸修改,并转为tensor)image = T.Resize(target_size)(image)image = T.ToTensor()(image)# Convert to Torch.Tensor and normalize. mean与std (RGB三通道)这里的参数和数据集中是对应的,训练过程中一致image = T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(image)# Add batch_size axis.增加一个维度,用于按batch测试 本次这里一次测试一张image = image[None]if use_gpu:image = image.cuda()return Variable(image, volatile=True) #不需要求导# 开启服务 这里的predict只是一个名字,可自定义
@app.route("/predict", methods=["POST"])
def predict():# Initialize the data dictionary that will be returned from the view.#做一个标志,刚开始无图像传入时为false,传入图像时为truedata = {"success": False}# Ensure an image was properly uploaded to our endpoint.# 如果收到请求if flask.request.method == 'POST':#判断是否为图像if flask.request.files.get("image"):# Read the image in PIL format# 将收到的图像进行读取image = flask.request.files["image"].read()image = Image.open(io.BytesIO(image)) #二进制数据# Preprocess the image and prepare it for classification.# 利用上面的预处理函数将读入的图像进行预处理image = prepare_image(image, target_size=(224, 224))# Classify the input image and then initialize the list of predictions to return to the client.preds = F.softmax(model(image), dim=1)results = torch.topk(preds.cpu().data, k=3, dim=1)results = (results[0].cpu().numpy(), results[1].cpu().numpy())#将data字典增加一个key,value,其中value为list格式data['predictions'] = list()# Loop over the results and add them to the list of returned predictionsfor prob, label in zip(results[0][0], results[1][0]):label_name = idx2label[label]r = {"label": label_name, "probability": float(prob)}#将预测结果添加至data字典data['predictions'].append(r)# Indicate that the request was a success.data["success"] = True# Return the data dictionary as a JSON response.# 将最终结果以json格式文件传出return flask.jsonify(data)if __name__ == '__main__':print("Loading PyTorch model and Flask starting server ...")print("Please wait until server has fully started")#先加载模型load_model()#再开启服务app.run()
调用模型(响应)
simple_request.py
import requests
import argparse# Initialize the PyTorch REST API endpoint URL.
PyTorch_REST_API_URL = 'http://127.0.0.1:5000/predict'def predict_result(image_path):# Initialize image pathimage = open(image_path, 'rb').read()payload = {'image': image}# Submit the request.r = requests.post(PyTorch_REST_API_URL, files=payload).json()# Ensure the request was successful.if r['success']:# Loop over the predictions and display them.for (i, result) in enumerate(r['predictions']):print('{}. {}: {:.4f}'.format(i + 1, result['label'],result['probability']))# Otherwise, the request failed.else:print('Request failed')if __name__ == '__main__':parser = argparse.ArgumentParser(description='Classification demo')parser.add_argument('--file',default='./dog.jpg', type=str, help='test image file')args = parser.parse_args()predict_result(args.file)
flask部署pytorch模型相关推荐
- 学习笔记|Flask部署Pytorch模型+Gunicorn+Docker
一.使用Flask部署Pytorch模型 其实原理很简单,我们希望使用一个已经训练好的pytorch模型,用它做预测或生成.我们的模型部署在服务器上,客户端可以通过http request调用我们部署 ...
- Sanic框架下部署Pytorch模型
前言 本文针对业余范围的Pytorch模型部署,类似各位想把自己开发的深度学习模型上线web端demo等等. 大家比较熟悉的Python框架主要有flask,使用flask部署上线深度学习模型过程简单 ...
- 在C++平台上部署PyTorch模型流程+踩坑实录
点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 导读 本文主要讲解如何将pytorch的模型部署到c++平台上的模 ...
- 经验 | 在C++平台上部署PyTorch模型流程+踩坑实录
点上方蓝字计算机视觉联盟获取更多干货 在右上方 ··· 设为星标 ★,与你不见不散 仅作学术分享,不代表本公众号立场,侵权联系删除 转载于:作者丨火星少女@知乎 来源丨https://zhuanlan ...
- 在Android设备部署PyTorch模型
Pytorch Mobile Android Demo 1 HelloWorldApp 1 模型准备 2 源码分析 3 读取图片数据 4 读取模型 5 将图像转换为Tensor 6 运行模型 7 处理 ...
- 解锁新姿势-使用TensorRT部署pytorch模型
一.整体流程概览 使用pytorch训练模型,生成*.pth文件 将*.pth转换成onnx模型 在tensorrt中加载onnx模型,并转换成trt的object 在trt中使用第三步转换的obje ...
- 西北乱跑娃 --- bottle框架部署pytorch模型
一.前言 在网站荡了很多关于深度学习的代码,包括在码云.github和各种博客.但是作者毕竟是一个文科生,也没有怎么接触过深度学习分类的代码,加上那些文章中的代码文件太多,极其晦涩难懂所以在之前的半年 ...
- flask部署pytorch
https://blog.csdn.net/dou3516/article/details/82912458
- 通过带Flask的REST API在Python中部署PyTorch
通过带Flask的REST API在Python中部署PyTorch 在本文中,将使用Flask来部署PyTorch模型,并用讲解用于模型推断的 REST API.特别是,将部署一个预训练的Dense ...
最新文章
- EX2010与EX2013共存迁移01-设计及说明
- 如何计算递归算法的时间复杂度
- union与struct的区别?
- JAVA实验报告九异常处理_Java课后练习9(异常处理)
- 页面残留数据该如何处理
- IMDb、烂番茄、MTC、各种电影行业评分名字整理
- 不要再被Python洗脑了!!
- 加密初衷是什么?安全性or实时性
- body标签子级被默认client width截断的解决方法
- 【OpenCV入门指南】第六篇 轮廓检测 下
- TOEFL 考场注意事项 考试须知
- 【渝粤教育】国家开放大学2018年秋季 2517T社区工作 参考试题
- 采用commons-emai发送电子邮件
- 如何对网络“黑灰产”实现精准打击?
- 灰度图像和彩色图像的直方图均衡化(python实现)
- PAT (Basic Level) Practice (中文)1027 打印沙漏 (20 分)(C++)
- 超文本传输协议(HTTP)
- 关于Symantec(赛门铁克)认证服务
- 系统动力学:非线性世界的视角
- Springboot集成Redis和Redis工具类
热门文章
- go 自定义error怎么判断是否相等_「GCTT 出品」Go 系列教程——30. 错误处理
- 华为手机投屏电脑_华为手机如何实现无线投屏?
- Traveling on the Axis 模拟
- 牛客 2021年度训练联盟热身训练赛第二场 E题NIH Budget
- 第八届“图灵杯”NEUQ-ACM程序设计竞赛个人赛——E题 Seek the Joker II
- 数学式子中arg min,arg max的含义
- Linux的学习笔记~
- python发QQ邮件
- 树莓派入门教程 - 0 - 准备篇 - 0.1 第一次开机
- LeetCode 159. 至多包含两个不同字符的最长子串 (滑动窗口哈希表)