Deploy Machine Learning Model using Flask
0 563
Introduction
Deploying a machine learning model to a web application allows users to interact with it easily through a browser. Flask, a lightweight Python web framework, provides a simple way to serve your ML models and create interactive interfaces. In this article, we will explore how to deploy a machine learning model using Flask.
Prerequisites
Before starting, make sure you have the following installed:
- Python 3.x
- Flask
- Scikit-learn (or any ML library you use)
- Joblib or Pickle for model serialization
Step 1: Train and Save Your Machine Learning Model
First, train your model using your preferred dataset and library. Once trained, save the model to disk so it can be loaded later by the Flask app.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import joblib
# Load dataset and train model
iris = load_iris()
X, y = iris.data, iris.target
model = RandomForestClassifier()
model.fit(X, y)
# Save the trained model
joblib.dump(model, 'model.pkl')
Step 2: Create a Flask App to Serve the Model
Set up a Flask application that loads the saved model and accepts input from users to make predictions.
from flask import Flask, request, jsonify
import joblib
import numpy as np
app = Flask(__name__)
model = joblib.load('model.pkl')
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
features = np.array(data['features']).reshape(1, -1)
prediction = model.predict(features)
return jsonify({'prediction': int(prediction[0])})
if __name__ == '__main__':
app.run(debug=True)
Step 3: Testing the API
You can test the model prediction endpoint using tools like Postman or curl. Send a POST request with JSON data containing the input features.
curl -X POST http://127.0.0.1:5000/predict -H "Content-Type: application/json" -d '{"features": [5.1, 3.5, 1.4, 0.2]}'
Step 4: Creating a Simple Frontend (Optional)
For a user-friendly experience, you can build an HTML form to collect inputs and display predictions. The Flask app can render this form and handle submissions seamlessly.
Best Practices
- Validate and sanitize input data to avoid errors.
- Use environment variables or config files to manage sensitive data.
- Consider using Docker for easier deployment and portability.
Conclusion
Using Flask to deploy a machine learning model is a straightforward and effective approach to make your model accessible via a web interface. This setup can be expanded with user authentication, advanced frontends, and scalable cloud hosting to build powerful AI-driven applications.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments