How to Run Batch Predictions with a Mock Model in Python
Build a lightweight mock model class and run predictions across a batch of samples, returning results as a plain Python list.
pip install numpy
Python code
23 linesimport numpy as np
class MockModel:
def __init__(self, weights):
self.weights = np.array(weights)
def predict(self, X):
return X @ self.weights
def predict_batch(model, batch):
"""Run predictions for a batch of samples and return results as a list."""
return model.predict(np.array(batch)).tolist()
if __name__ == "__main__":
model = MockModel([0.5, -1.2, 0.8])
batch = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
results = predict_batch(model, batch)
print("Predictions:", results)
print("Batch size:", len(results))
Output
Predictions: [0.5, 1.4, 2.3000000000000003]
Batch size: 3
How it works
The MockModel class wraps a simple linear transformation using NumPy's matrix multiplication. The predict_batch function converts the input batch into a NumPy array, applies the model's predict method, and then converts the result back to a list for easy consumption. This pattern mirrors how real ML models accept a matrix of features and return an array of predictions. Running the script under if __name__ == '__main__' ensures the demo only executes when the file is run directly, not when imported.
Common mistakes
- Forgetting to convert the batch to a NumPy array before matrix multiplication
- Assuming the predict method returns a list instead of a NumPy array
- Mixing up the shape of weights — weights must match the number of features in each sample
Variations
- Use a library like scikit-learn's predict method for a more realistic model object
- Batch predictions in chunks to avoid loading all data into memory at once
Real-world use cases
- Running inference on a batch of user feature vectors in an online recommendation system.
- Scoring multiple input rows from a CSV before writing predictions back to storage.
- Wrapping a mock or stub model in unit tests to verify batch data flow without heavy dependencies.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.