对于数据迷信我的项目来说,咱们始终都很关注模型的训练和体现,然而在理论工作中如何启动和运行咱们的模型是模型上线的最初一步也是最重要的工作。
明天我将通过一个简略的案例:部署一个PyTorch图像分类模型,介绍这个最重要的步骤。
咱们这里应用PyTorch和Flask。能够应用pip install torch和pip install flask装置这些包。
web利用
为Flask创立一个文件app.py和一个路由:
fromflaskimportFlask
importtorch
app=Flask(__name__)
@app.route('/')
defhome():
return'Welcome to the PyTorch Flask app!'
当初咱们能够运行python app.py,如果没有问题,你能够拜访http://localhost:5000/,应该会看到一条简略的音讯——“Welcome to the PyTorch Flask app!”
这就阐明咱们flask的web服务曾经能够工作了,当初让咱们增加一些代码,将数据传递给咱们的模型!
增加更多的导入
fromflaskimportFlask, request, render_template
fromPILimportImage
importtorch
importtorchvision.transformsastransforms
而后再将主页的内容换成一个HTML页面
@app.route('/')
defhome():
returnrender_template('home.html')
创立一个templates文件夹,而后创立home.html。
<html>
<head>
<title>PyTorch Image Classification</title>
</head>
<body>
<h1>PyTorch Image Classification</h1>
<formmethod="POST"enctype="multipart/form-data"action="/predict">
<inputtype="file"name="image">
<inputtype="submit"value="Predict">
</form>
</body>
</html>
HTML非常简单——有一个上传按钮,能够上传咱们想要运行模型的任何数据(在咱们的例子中是图像)。
以上都是根本的web利用的内容,上面就是要将这个web利用和咱们的pytorch模型的推理联合。
加载模型
在home route下面,加载咱们的模型。
model=torch.jit.load('path/to/model.pth')
咱们都晓得,模型的输出是张量,所以对于图片来说,咱们须要将其转换为张量、还要进行例如调整大小或其余模式的预处理(这与训练时的解决一样)。
咱们解决的是图像,所以预处理很简略
defprocess_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)
returnimage_tensor
咱们还须要一个数组来示意类,本文只有2类
class_names= ['apple', 'banana']
预测
下一步就是创立一个路由,接管上传的图像,解决并应用模型进行预测,并返回每个类的概率。
@app.route('/predict', methods=['POST'])
defpredict():
# 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=lambdax: x[1], reverse=True)
# Render HTML page with prediction results
returnrender_template('predict.html', class_probs=class_probs,
predicted_class=predicted_class, probability=probability)
咱们的/predict路由首先应用softmax函数取得类概率,而后取得最高概率的索引。它应用这个索引在类名列表中查找预测的类,并取得该类的概率。而后按降序对类别概率进行排序,并返回预测后果。
最初,咱们的app.py文件应该是这样的:
fromflaskimportFlask, request, render_template
fromPILimportImage
importtorch
importtorchvision.transformsastransforms
model=torch.jit.load('path/to/model.pth')
@app.route('/')
defhome():
returnrender_template('home.html')
defprocess_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)
returnimage_tensor
class_names= ['apple', 'banana'] #REPLACE THIS WITH YOUR CLASSES
@app.route('/predict', methods=['POST'])
defpredict():
# 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=lambdax: x[1], reverse=True)
# Render HTML page with prediction results
returnrender_template('predict.html', class_probs=class_probs,
predicted_class=predicted_class, probability=probability)
最初一个局部是实现predict.html模板,在templates目录创立一个名为predict.html的文件:
<html>
<head>
<title>PredictionResults</title>
</head>
<body>
<h1>PredictionResults</h1>
<p>PredictedClass: {{ predicted_class }}</p>
<p>Probability: {{ probability }}</p>
<h2>OtherClasses</h2>
<ul>
{%forclass_name, probinclass_probs%}
<li>{{ class_name }}: {{ prob }}</li>
{%endfor%}
</ul>
</body>
</html>
这个HTML页面显示了预测的类别和概率,以及按概率降序排列的其余类别列表。
测试
应用python app.py运行服务,而后首页会显示咱们创立的上传图片的按钮,能够通过按钮上传图片进行测试,这里咱们还能够通过编程形式发送POST申请来测试您的模型。
上面就是发送POST申请的Python代码
#pip install requests
importrequests
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模型。
https://avoid.overfit.cn/post/4984d0f355b7448c8efd70aee9677739
作者:Daniel Korsz
发表回复