How to Deploy a Machine Learning Model with Flask: A Step-by-Step Guide
Deploying a machine learning model makes it accessible via an API so users or applications can send data and receive predictions. Flask, a lightweight Python web framework, is ideal for wrapping a trained model into a simple REST service. This guide walks you through the essential steps to get your model online quickly.
Before you start, ensure you have a trained model saved (e.g., as a .pkl file using joblib or pickle) and Flask installed (pip install flask). You’ll also need any libraries your model depends on, like scikit-learn or numpy.
1. Load Your Trained Model
In your Flask app script (app.py), load the model at the top level so it’s available globally. This avoids reloading the model on every request, saving time and resources.
- Use
joblib.load('model.pkl')orpickle.load()to deserialize your model. - Load any required encoders, scalers, or vectorizers the same way.
2. Create Flask Endpoints
Set up a route (e.g., /predict) that accepts POST requests. The endpoint will receive JSON input, run the prediction, and return the result as JSON.
- Decorate the function with
@app.route('/predict', methods=['POST']). - Extract incoming JSON using
request.get_json().
3. Preprocess Input and Return Predictions
Transform the input data to match your model’s expected format (e.g., convert list to numpy array, apply scaling). Run the prediction and format the output.
- Apply the same preprocessing steps used during training.
- Return
jsonify({'prediction': prediction.tolist()}).
4. Run the Server
Add the standard Flask runner at the bottom of your script:
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=5000)
That’s it! Your machine learning model is now deployed as a Flask API. Test it with a tool like curl or Postman by sending a POST request with sample data. With this foundation, you can add authentication, logging, or scale using a production WSGI server like Gunicorn.