The user wants a program that implements machine learning model inference.
This is a very broad request. "Inference" means using a trained model to make predictions on new data.
To provide a useful answer, I need to make some choices about:
The Language: Python is the de facto standard for ML.
The Framework: Scikit-learn is great for beginners/classical ML. PyTorch and TensorFlow are better for deep learning. I should probably provide a simple example using Scikit-learn (because it's built-in and easy) and maybe a "hello world" style deep learning example using PyTorch or TensorFlow, or just explain the general concept.
The Model: I need a pre-trained model. I can either train one quickly within the script or load a saved one. Training a quick one makes the script self-contained and runnable, which is better for demonstration.
The Data: I need some dummy data (like the Iris dataset or generated numbers).
Plan:
Conceptual Explanation: Briefly explain what inference is (taking input -> model -> output).
Approach 1: Classical ML (Scikit-learn):
Use the Iris dataset (standard, easy to understand).
Train a simple model (e.g., Random Forest or Logistic Regression).
Save the model (using joblib or pickle) to simulate a real-world workflow where training and inference are separate.
Write the "Inference" part: Load model -> Input data -> Predict.
Approach 2: Deep Learning (PyTorch or TensorFlow):
This might be too complex for a generic request, but I should mention it or provide a very simple version. Let's stick to a simple PyTorch example of loading a pre-defined architecture and running a tensor through it.
Self-correction: Let's stick to Scikit-learn for the main, runnable code because it's most likely what a generalist asking this question needs. I can add a PyTorch section if I want to be thorough, but maybe keep it simple first.
Better idea: I will provide a complete Python script using Scikit-learn because it's the most "standard" way to show the concept without getting bogged down in tensor management.
Refining the Scikit-learn Example:
Step 1: Train a model on Iris data.
Step 2: Save it to a file (model.joblib).
Step 3: In a separate "inference" function/block, load the model.
Step 4: Take a new sample (sepal/petal length/width).
Step 5: Print the prediction.
Refining for "Production-like" feel:
Even though it's a script, I should structure it to look like a function or a class that handles the input.
I should show how to handle raw input (lists) and convert it to the format the model expects (numpy arrays).
What if they want a web API?
Often "implement inference" implies a service. I should briefly mention or show a tiny Flask or FastAPI example, as that's how inference is actually exposed in the real world.
Example 2: Web API (Flask/FastAPI): This is crucial for real-world context. A model sitting in a script is rarely "production" inference. A REST API is the standard interface.
Example 3: Deep Learning (Brief PyTorch): Just to show the difference (tensor handling).
Let's write the code for the Scikit-learn version first mentally.
python
# Train
clf = RandomForestClassifier()
clf.fit(X, y)
dump(clf, 'model.joblib')
# Inference
model = load('model.joblib')
pred = model.predict([[5.1, 3.5, 1.4, 0.2]])
Simple enough.
Now the Flask version.
python
app = Flask(__name__)
model = load('model.joblib')
@app.route('/predict', methods=['POST'])
def predict():
data = request.json
pred = model.predict([data['features']])
return jsonify({'prediction': int(pred[0])})
This adds huge value.
Final Decision on Content:
I will provide a comprehensive answer focusing on Scikit-learn for the logic, and Flask for the deployment aspect, as these represent the two main steps of "implementing inference".
Drafting the response:
Section 1: The Core Logic (Scikit-learn). Script that trains, saves, loads, and predicts.
Section 2: The Production Deployment (Flask). Script that serves the model via HTTP.
Section 3: Deep Learning Note. Briefly mention PyTorch/TensorFlow requires similar steps but with tensor conversion.
Let's ensure the code is copy-paste runnable.
I will use the Iris dataset so the user doesn't need to download external CSV files.
Double Check:
Did the user specify a language? No. Assume Python.
Did they specify a type of ML? No. Assume Classification (easiest to understand).
Okay, I'm ready to write the solution. I'll start with the simple script, then move to the API example.
Self-Correction during drafting: Make sure to handle the imports clearly.
Imports: sklearn, joblib, numpy, flask.
Step-by-step guide:
Setup dependencies.
train.py: Create and save the model.
inference.py (or app.py): Load model and run logic.
Actually, keeping it in one file for the first example makes it easier to run. I will write one file that does training first, then inference immediately, to demonstrate the flow, then explain that in reality these are separated.
Let's go with a modular approach:
Basic Inference Script (Standard Scikit-Learn).
Web API Inference (Using Flask - how it's actually used in industry).
This covers "How to code it" and "How to serve it".
To implement machine learning model inference, you generally need three things:
A Trained Model: A file containing the learned weights and architecture.
Input Data: New data that the model hasn't seen before, formatted correctly.
An Inference Engine: A script (usually Python) that loads the model and feeds the data through it to get a prediction.
Below are two examples. Example 1 is a simple local script using scikit-learn. Example 2 is how to serve a model as a REST API (a real-world production scenario) using Flask.
Prerequisites
You will need to install the necessary libraries:
bash
pip install scikit-learn numpy flask joblib
Example 1: Basic Inference Script (Local)
This approach is used for batch processing or running models on your local machine. We will train a simple model on the classic "Iris" dataset, save it to disk, and then load it back up to perform inference on a new data point.
python
import joblib
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# ---------------------------------------------------------
# STEP 1: Training and Saving the Model
# (In a real scenario, you would already have a trained model file)
# ---------------------------------------------------------
def train_and_save_model():
# Load sample data
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 a simple classifier
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Save the model to a file using joblib
model_filename = 'iris_model.joblib'
joblib.dump(model, model_filename)
print(f"Model trained and saved to {model_filename}")
return model_filename
# ---------------------------------------------------------
# STEP 2: Inference (Loading and Predicting)
# This is the code you would run when you have new data
# ---------------------------------------------------------
def run_inference(model_path, new_data):
# 1. Load the trained model
try:
model = joblib.load(model_path)
print("Model loaded successfully.")
except FileNotFoundError:
print("Model file not found.")
return
# 2. Preprocess input (ensure it's a 2D array)
# Scikit-learn expects shape (n_samples, n_features)
input_features = np.array(new_data).reshape(1, -1)
# 3. Run Inference
prediction = model.predict(input_features)
probabilities = model.predict_proba(input_features)
# 4. Decode result
iris = load_iris()
class_name = iris.target_names[prediction[0]]
print(f"\n--- Inference Result ---")
print(f"Input Features: {new_data}")
print(f"Predicted Class: {class_name}")
print(f"Confidence Scores: {probabilities[0]}")
# --- Main Execution ---
if __name__ == "__main__":
# A. Create the model file (Run once)
filename = train_and_save_model()
# B. Simulate receiving new data
# Example: [sepal length, sepal width, petal length, petal width]
new_flower_measurements = [5.1, 3.5, 1.4, 0.2]
# C. Run Inference
run_inference(filename, new_flower_measurements)
Example 2: Production Inference (REST API)
In the real world, inference is often done via a web server. A mobile app or website sends data to your Python server as JSON, and the server returns the prediction.
Here is how you implement that using Flask:
python
from flask import Flask, request, jsonify
import joblib
import numpy as np
app = Flask(__name__)
# Load the model once when the server starts
# (Ensure you have run the code from Example 1 to generate this file first)
MODEL_PATH = 'iris_model.joblib'
model = None
def load_model():
global model
try:
model = joblib.load(MODEL_PATH)
print("Model loaded for API.")
except:
print("Model not found. Run the training script first.")
@app.route('/predict', methods=['POST'])
def predict():
# 1. Check if model is loaded
if model is None:
return jsonify({'error': 'Model not loaded'}), 500
# 2. Get data from the JSON body
data = request.get_json()
# Expecting JSON like: { "features": [5.1, 3.5, 1.4, 0.2] }
features = data.get('features', [])
if not features:
return jsonify({'error': 'No features provided'}), 400
# 3. Convert to numpy array and reshape
input_array = np.array(features).reshape(1, -1)
# 4. Run Inference
prediction_index = model.predict(input_array)[0]
probability = model.predict_proba(input_array).max()
# 5. Map index to class name (Iris dataset mapping)
class_names = ['setosa', 'versicolor', 'virginica']
predicted_class = class_names[prediction_index]
# 6. Return JSON response
return jsonify({
'prediction': predicted_class,
'confidence': float(probability)
})
if __name__ == '__main__':
load_model()
# Run the server
app.run(debug=True, port=5000)
How to use the API:
Run the script above.
Open a tool like Postman or use curl in your terminal:
You will receive a JSON response: {"confidence": 1.0, "prediction": "setosa"}
Key Considerations for Inference Code
Input Shape: Always check input.reshape(1, -1). Models almost always expect a list of items (batch processing), even if you are only sending one item.
Preprocessing: The input data during inference must be preprocessed exactly the same way it was during training (e.g., scaling/normalization). If you scaled your training data with a StandardScaler, you must save that scaler and apply it to the input data before prediction.
Performance:joblib and pickle are standard for Python. For large Deep Learning models (PyTorch/TensorFlow), they use specific formats (.pt / .h5) optimized for large tensor operations.