如何用python加flask进行模型部署,代码示例
时间: 2024-05-02 15:20:43 浏览: 14
很高兴为您回答问题。以下是一个简单的使用 Python 和 Flask 进行模型部署的示例代码:
```python
from flask import Flask, jsonify, request
import numpy as np
import tensorflow as tf
app = Flask(__name__)
# Load the model
model = tf.keras.models.load_model('path/to/your/model')
# Define a route for model inference
@app.route('/predict', methods=['POST'])
def predict():
# Get the input data from the POST request
input_data = request.get_json()['input_data']
# Preprocess the input data if necessary
# For example, convert text to numerical features
# Make a prediction using the model
prediction = model.predict(np.array([input_data]))
# Postprocess the prediction if necessary
# For example, convert numerical output to text
# Return the prediction as a JSON response
return jsonify({'prediction': prediction.tolist()})
if __name__ == '__main__':
app.run(debug=True)
```
这个示例使用 Flask 来创建一个可以接受 POST 请求并返回 JSON 格式的模型部署服务。您可以根据自己的需求,修改这个示例来适应您的模型部署需求。请注意,这个示例并没有考虑到生产环境的安全性和可扩展性。在实际部署中,您需要考虑更多的安全性和可扩展性方面的问题。