使用Flask快速部署PyTorch模型
对于数据科学项目来说,我们一直都很关注模型的训练和表现,但是在实际工作中如何启动和运行我们的模型是模型上线的最后一步也是最重要的工作。
今天我将通过一个简单的案例:部署一个PyTorch图像分类模型,介绍这个最重要的步骤。
我们这里使用PyTorch和Flask。可以使用pip install torch和pip install flask安装这些包。
web应用
为Flask创建一个文件app.py和一个路由:
from flask import Flask
import torch
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to the PyTorch Flask app!'
现在我们可以运行python app.py,如果没有问题,你可以访问http://localhost:5000/,应该会看到一条简单的消息——“Welcome to the PyTorch Flask app!”
这就说明我们flask的web服务已经可以工作了,现在让我们添加一些代码,将数据传递给我们的模型!
添加更多的导入
from flask import Flask, request, render_template
from PIL import Image
import torch
import torchvision.transforms as transforms
然后再将主页的内容换成一个HTML页面
@app.route('/')
def home():
return render_template('home.html')
创建一个templates文件夹,然后创建home.html。
<html>
<head>
<title>PyTorch Image Classification</title>
</head>
<body>
<h1>PyTorch Image Classification</h1>
<form method="POST" enctype="multipart/form-data" action="/predict">
<input type="file" name="image">
<input type="submit" value="Predict">
</form>
</body>
</html>
HTML非常简单——有一个上传按钮,可以上传我们想要运行模型的任何数据(在我们的例子中是图像)。
以上都是基本的web应用的内容,下面就是要将这个web应用和我们的pytorch模型的推理结合。
加载模型
在home route上面,加载我们的模型。
model = torch.jit.load('path/to/model.pth')
我们都知道,模型的输入是张量,所以对于图片来说,我们需要将其转换为张量、还要进行例如调整大小或其他形式的预处理(这与训练时的处理一样)。
我们处理的是图像,所以预处理很简单
def process_image(image):
# Preprocess image for model
transformation = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
image_tensor = transformation(image).unsqueeze(0)
return image_tensor
我们还需要一个数组来表示类,本文只有2类
class_names = ['apple', 'banana']
预测
下一步就是创建一个路由,接收上传的图像,处理并使用模型进行预测,并返回每个类的概率。
@app.route('/predict', methods=['POST'])
def predict():
# Get uploaded image file
image = request.files['image']
# Process image and make prediction
image_tensor = process_image(Image.open(image))
output = model(image_tensor)
# Get class probabilities
probabilities = torch.nn.functional.softmax(output, dim=1)
probabilities = probabilities.detach().numpy()[0]
# Get the index of the highest probability
class_index = probabilities.argmax()
# Get the predicted class and probability
predicted_class = class_names[class_index]
probability = probabilities[class_index]
# Sort class probabilities in descending order
class_probs = list(zip(class_names, probabilities))
class_probs.sort(key=lambda x: x[1], reverse=True)
# Render HTML page with prediction results
return render_template('predict.html', class_probs=class_probs,
predicted_class=predicted_class, probability=probability)
我们的/predict路由首先使用softmax函数获得类概率,然后获得最高概率的索引。它使用这个索引在类名列表中查找预测的类,并获得该类的概率。然后按降序对类别概率进行排序,并返回预测结果。
最后,我们的app.py文件应该是这样的:
from flask import Flask, request, render_template
from PIL import Image
import torch
import torchvision.transforms as transforms
model = torch.jit.load('path/to/model.pth')
@app.route('/')
def home():
return render_template('home.html')
def process_image(image):
# Preprocess image for model
transformation = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
image_tensor = transformation(image).unsqueeze(0)
return image_tensor
class_names = ['apple', 'banana'] #REPLACE THIS WITH YOUR CLASSES
@app.route('/predict', methods=['POST'])
def predict():
# Get uploaded image file
image = request.files['image']
# Process image and make prediction
image_tensor = process_image(Image.open(image))
output = model(image_tensor)
# Get class probabilities
probabilities = torch.nn.functional.softmax(output, dim=1)
probabilities = probabilities.detach().numpy()[0]
# Get the index of the highest probability
class_index = probabilities.argmax()
# Get the predicted class and probability
predicted_class = class_names[class_index]
probability = probabilities[class_index]
# Sort class probabilities in descending order
class_probs = list(zip(class_names, probabilities))
class_probs.sort(key=lambda x: x[1], reverse=True)
# Render HTML page with prediction results
return render_template('predict.html', class_probs=class_probs,
predicted_class=predicted_class, probability=probability)
最后一个部分是实现predict.html模板,在templates目录创建一个名为predict.html的文件:
<html>
<head>
<title>Prediction Results</title>
</head>
<body>
<h1>Prediction Results</h1>
<p>Predicted Class: {{ predicted_class }}</p>
<p>Probability: {{ probability }}</p>
<h2>Other Classes</h2>
<ul>
{% for class_name, prob in class_probs %}
<li>{{ class_name }}: {{ prob }}</li>
{% endfor %}
</ul>
</body>
</html>
这个HTML页面显示了预测的类别和概率,以及按概率降序排列的其他类别列表。
测试
使用python app.py运行服务,然后首页会显示我们创建的上传图片的按钮,可以通过按钮上传图片进行测试,这里我们还可以通过编程方式发送POST请求来测试您的模型。
下面就是发送POST请求的Python代码
#pip install requests
import requests
url = 'http://localhost:5000/predict'
# Set image file path
image_path = 'path/to/image.jpg'
# Read image file and set as payload
image = open(image_path, 'rb')
payload = {'image': image}
# Send POST request with image and get response
response = requests.post(url, headers=headers, data=payload)
print(response.text)
这段代码将向Flask应用程序发送一个POST请求,上传指定的图像文件。我们创建的Flask应用程会处理图像,做出预测并返回响应,最后响应将打印到控制台。
就是这样只要5分钟,我们就可以成功地部署一个ML模型。
作者:Daniel Korsz
相关文章
- 基于Python的人脸识别考勤监控
- Python答题游戏
- Python调用百度API实现图像识别
- Python全栈疫情分析项目
- Python-基础-if语句快速入门
- Python-基础-循环语句快速入门
- Python-GUI签名
- 【2】VScode 搭建python和tensorflow环境
- python 简易时钟
- 【1】windows系统如何安装后缀是whl的python库
- 【2】超级详细Python-matplotlib画图,手把手教你画图!(线条颜色、大小、线形、标签)
- 【4】python读写文件操作---详细讲解!
- 【2】Anaconda下:ipython文件的打开方式,Jupyter Notebook中运行.py文件,快速打开ipython文件的方法!
- 【编写环境一】遇到常见python函数处理方式
- 【编写环境二】python库scipy.stats各种分布函数生成、以及随机数生成【泊松分布、正态分布等】
- Python xlwt数据保存到 Excel中以及xlrd读取excel文件画图
- 强化学习技巧三:Python多进程
- 强化学习技巧五:numba提速python程序
- 【7】python_matplotlib 输出(保存)矢量图方法;画图时图例说明(legend)放到图像外侧;Python_matplotlib图例放在外侧保存时显示不完整问题解决
- 【8】python_matplotlib改变横坐标和纵坐标上的刻度(ticks)、sagemath-list_plot()调整图例(legend)中点的数量、Matplotlib画各种论文图