Model Pipeline - REST API inference
This pipeline shows how a trained PyTorch model receives data through a REST API, processes it, and returns predictions. It covers data input, preprocessing, model inference, and output formatting.
This pipeline shows how a trained PyTorch model receives data through a REST API, processes it, and returns predictions. It covers data input, preprocessing, model inference, and output formatting.
Loss
1.2 |****
1.0 |***
0.8 |**
0.6 |**
0.4 |*
0.2 |
+----------------
1 2 3 4 5 Epochs| Epoch | Loss ↓ | Accuracy ↑ | Observation |
|---|---|---|---|
| 1 | 1.20 | 0.45 | Model starts learning with high loss and low accuracy |
| 2 | 0.85 | 0.65 | Loss decreases and accuracy improves |
| 3 | 0.60 | 0.78 | Model continues to improve |
| 4 | 0.45 | 0.85 | Good convergence with lower loss and higher accuracy |
| 5 | 0.35 | 0.90 | Training stabilizes with strong performance |
torch.no_grad() context to turn off gradient tracking during inference.model.train() enables training mode, torch.enable_grad() enables gradients, and model.backward() is invalid.from flask import Flask, request, jsonify
import torch
app = Flask(__name__)
model = torch.nn.Linear(2, 1)
model.eval()
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
x = torch.tensor(data['input']).unsqueeze(0).float()
with torch.no_grad():
output = model(x)
return jsonify({'prediction': output.item()})output.item(), which returns a float, then wrapped in JSON.@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
x = torch.tensor(data['input'])
with torch.no_grad():
output = model(x)
return jsonify({'prediction': output.item()}).float() before passing to the model.model.eval().torch.no_grad() to disable gradients, get prediction, and return JSON response.Pass the test and this pattern moves unknown