Sure, I can walk you through a simple example of how you might deploy a machine learning model using Flask, which is a lightweight web framework for Python. This approach is common when deploying models as a RESTful API service for smaller-scale applications.
Example: Deploying a Scikit-learn Model with Flask
Let's say you have a trained machine learning model using Scikit-learn, such as a simple classifier for the Iris dataset. Here's a basic outline of how you can create a deployable API using Flask.
1. Train and Save Your Model
First, ensure your model is trained and saved:
# train_model.py
import pickle
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# Load dataset
iris = load_iris()
X, y = iris.data, iris.target
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Save model to a file
with open('model.pkl', 'wb') as model_file:
pickle.dump(model, model_file)
2. Create a Flask App
Create a Flask app that loads this model and exposes an endpoint for predictions.
# app.py
import pickle
from flask import Flask, request, jsonify
# Load model
with open('model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
# Initialize Flask app
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
# Get JSON input
data = request.json
# Extract features from JSON input
features = data.get('features')
# Perform prediction
prediction = model.predict([features])
# Return the result as JSON
return jsonify({'prediction': int(prediction[0])})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
3. Run Your Flask App
Start your Flask app in the terminal:
python app.py
This will start a local server on http://localhost:5000, where you can interact with your model.
4. Make Predictions Through the API
You can test the API using any HTTP client like requests in Python or Postman. Here's how you might do it with Python:
import requests
# Example feature set for prediction
features = [5.1, 3.5, 1.4, 0.2] # Example input data from the Iris dataset
# Send POST request
response = requests.post("http://localhost:5000/predict", json={"features": features})
# Check the response status and content
if response.status_code == 200:
prediction = response.json().get('prediction')
print(f"Predicted class: {prediction}")
else:
print("Error:", response.text)
5. Deploying the API
To deploy this Flask application, you can use platforms like Heroku, AWS Elastic Beanstalk, or Docker. You'd need to create a suitable Dockerfile to containerize your application if that's your preferred deployment method, or configure the necessary server settings if deploying directly to a cloud service.
This simple setup shows how to make your machine learning model accessible via a web service, where external applications can send HTTP requests to get predictions in real-time.