0


使用Flask快速部署PyTorch模型

对于数据科学项目来说,我们一直都很关注模型的训练和表现,但是在实际工作中如何启动和运行我们的模型是模型上线的最后一步也是最重要的工作。

今天我将通过一个简单的案例:部署一个PyTorch图像分类模型,介绍这个最重要的步骤。

我们这里使用PyTorch和Flask。可以使用pip install torch和pip install flask安装这些包。

web应用

为Flask创建一个文件app.py和一个路由:

  1. fromflaskimportFlask
  2. importtorch
  3. app=Flask(__name__)
  4. @app.route('/')
  5. defhome():
  6. return'Welcome to the PyTorch Flask app!'

现在我们可以运行python app.py,如果没有问题,你可以访问http://localhost:5000/,应该会看到一条简单的消息——“Welcome to the PyTorch Flask app!”

这就说明我们flask的web服务已经可以工作了,现在让我们添加一些代码,将数据传递给我们的模型!

添加更多的导入

  1. fromflaskimportFlask, request, render_template
  2. fromPILimportImage
  3. importtorch
  4. importtorchvision.transformsastransforms

然后再将主页的内容换成一个HTML页面

  1. @app.route('/')
  2. defhome():
  3. returnrender_template('home.html')

创建一个templates文件夹,然后创建home.html。

  1. <html>
  2. <head>
  3. <title>PyTorch Image Classification</title>
  4. </head>
  5. <body>
  6. <h1>PyTorch Image Classification</h1>
  7. <formmethod="POST"enctype="multipart/form-data"action="/predict">
  8. <inputtype="file"name="image">
  9. <inputtype="submit"value="Predict">
  10. </form>
  11. </body>
  12. </html>

HTML非常简单——有一个上传按钮,可以上传我们想要运行模型的任何数据(在我们的例子中是图像)。

以上都是基本的web应用的内容,下面就是要将这个web应用和我们的pytorch模型的推理结合。

加载模型

在home route上面,加载我们的模型。

  1. model=torch.jit.load('path/to/model.pth')

我们都知道,模型的输入是张量,所以对于图片来说,我们需要将其转换为张量、还要进行例如调整大小或其他形式的预处理(这与训练时的处理一样)。

我们处理的是图像,所以预处理很简单

  1. defprocess_image(image):
  2. # Preprocess image for model
  3. transformation=transforms.Compose([
  4. transforms.Resize(256),
  5. transforms.CenterCrop(224),
  6. transforms.ToTensor(),
  7. transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  8. ])
  9. image_tensor=transformation(image).unsqueeze(0)
  10. returnimage_tensor

我们还需要一个数组来表示类,本文只有2类

  1. class_names= ['apple', 'banana']

预测

下一步就是创建一个路由,接收上传的图像,处理并使用模型进行预测,并返回每个类的概率。

  1. @app.route('/predict', methods=['POST'])
  2. defpredict():
  3. # Get uploaded image file
  4. image=request.files['image']
  5. # Process image and make prediction
  6. image_tensor=process_image(Image.open(image))
  7. output=model(image_tensor)
  8. # Get class probabilities
  9. probabilities=torch.nn.functional.softmax(output, dim=1)
  10. probabilities=probabilities.detach().numpy()[0]
  11. # Get the index of the highest probability
  12. class_index=probabilities.argmax()
  13. # Get the predicted class and probability
  14. predicted_class=class_names[class_index]
  15. probability=probabilities[class_index]
  16. # Sort class probabilities in descending order
  17. class_probs=list(zip(class_names, probabilities))
  18. class_probs.sort(key=lambdax: x[1], reverse=True)
  19. # Render HTML page with prediction results
  20. returnrender_template('predict.html', class_probs=class_probs,
  21. predicted_class=predicted_class, probability=probability)

我们的/predict路由首先使用softmax函数获得类概率,然后获得最高概率的索引。它使用这个索引在类名列表中查找预测的类,并获得该类的概率。然后按降序对类别概率进行排序,并返回预测结果。

最后,我们的app.py文件应该是这样的:

  1. fromflaskimportFlask, request, render_template
  2. fromPILimportImage
  3. importtorch
  4. importtorchvision.transformsastransforms
  5. model=torch.jit.load('path/to/model.pth')
  6. @app.route('/')
  7. defhome():
  8. returnrender_template('home.html')
  9. defprocess_image(image):
  10. # Preprocess image for model
  11. transformation=transforms.Compose([
  12. transforms.Resize(256),
  13. transforms.CenterCrop(224),
  14. transforms.ToTensor(),
  15. transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  16. ])
  17. image_tensor=transformation(image).unsqueeze(0)
  18. returnimage_tensor
  19. class_names= ['apple', 'banana'] #REPLACE THIS WITH YOUR CLASSES
  20. @app.route('/predict', methods=['POST'])
  21. defpredict():
  22. # Get uploaded image file
  23. image=request.files['image']
  24. # Process image and make prediction
  25. image_tensor=process_image(Image.open(image))
  26. output=model(image_tensor)
  27. # Get class probabilities
  28. probabilities=torch.nn.functional.softmax(output, dim=1)
  29. probabilities=probabilities.detach().numpy()[0]
  30. # Get the index of the highest probability
  31. class_index=probabilities.argmax()
  32. # Get the predicted class and probability
  33. predicted_class=class_names[class_index]
  34. probability=probabilities[class_index]
  35. # Sort class probabilities in descending order
  36. class_probs=list(zip(class_names, probabilities))
  37. class_probs.sort(key=lambdax: x[1], reverse=True)
  38. # Render HTML page with prediction results
  39. returnrender_template('predict.html', class_probs=class_probs,
  40. predicted_class=predicted_class, probability=probability)

最后一个部分是实现predict.html模板,在templates目录创建一个名为predict.html的文件:

  1. <html>
  2. <head>
  3. <title>PredictionResults</title>
  4. </head>
  5. <body>
  6. <h1>PredictionResults</h1>
  7. <p>PredictedClass: {{ predicted_class }}</p>
  8. <p>Probability: {{ probability }}</p>
  9. <h2>OtherClasses</h2>
  10. <ul>
  11. {%forclass_name, probinclass_probs%}
  12. <li>{{ class_name }}: {{ prob }}</li>
  13. {%endfor%}
  14. </ul>
  15. </body>
  16. </html>

这个HTML页面显示了预测的类别和概率,以及按概率降序排列的其他类别列表。

测试

使用python app.py运行服务,然后首页会显示我们创建的上传图片的按钮,可以通过按钮上传图片进行测试,这里我们还可以通过编程方式发送POST请求来测试您的模型。

下面就是发送POST请求的Python代码

  1. #pip install requests
  2. importrequests
  3. url='http://localhost:5000/predict'
  4. # Set image file path
  5. image_path='path/to/image.jpg'
  6. # Read image file and set as payload
  7. image=open(image_path, 'rb')
  8. payload= {'image': image}
  9. # Send POST request with image and get response
  10. response=requests.post(url, headers=headers, data=payload)
  11. print(response.text)

这段代码将向Flask应用程序发送一个POST请求,上传指定的图像文件。我们创建的Flask应用程会处理图像,做出预测并返回响应,最后响应将打印到控制台。

就是这样只要5分钟,我们就可以成功地部署一个ML模型。

作者:Daniel Korsz

“使用Flask快速部署PyTorch模型”的评论:

还没有评论