
From notebook to endpoint: training a model and serving it as an API
Train a simple scikit-learn model, save it, and serve predictions through a Flask API, a first step toward deploying ML on AWS.
Step 1: Train and save
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import joblib
from sklearn.ensemble import RandomForestClassifier
import joblib
X, y = load_iris(return_X_y=True)
model = RandomForestClassifier().fit(X, y)
joblib.dump(model, "model.joblib")
model = RandomForestClassifier().fit(X, y)
joblib.dump(model, "model.joblib")
Step 2: Serve with Flask
from flask import Flask, request, jsonify
import joblib
import joblib
app = Flask(__name__)
model = joblib.load("model.joblib")
model = joblib.load("model.joblib")
@app.post("/predict")
def predict():
features = request.json["features"]
return jsonify(prediction=int(model.predict([features])[0]))
def predict():
features = request.json["features"]
return jsonify(prediction=int(model.predict([features])[0]))
Step 3: Test
curl -X POST localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"features":[5.1,3.5,1.4,0.2]}'
-H "Content-Type: application/json" \
-d '{"features":[5.1,3.5,1.4,0.2]}'
Next: deploy on AWS
Package the app in a Docker container and run it on Elastic Beanstalk or EC2. Add input validation and logging before sharing it.
Package the app in a Docker container and run it on Elastic Beanstalk or EC2. Add input validation and logging before sharing it.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article