Build a Mock Random Forest Classifier in Python
Create a simple random-forest-like classifier with random majority voting between trees, including fit, predict, and predict_proba methods.
Python code
43 linesimport random
class MockRandomForest:
def __init__(self, n_trees=10, random_state=42):
self.n_trees = n_trees
self.random_state = random_state
self.classes_ = None
self._class_counts = None
random.seed(random_state)
def fit(self, X, y):
self.classes_ = sorted(set(y))
self._class_counts = {cls: y.count(cls) for cls in self.classes_}
return self
def predict(self, X):
predictions = []
for _ in range(len(X)):
# Each "tree" picks a random class
votes = [random.choice(self.classes_) for _ in range(self.n_trees)]
# Majority vote
prediction = max(set(votes), key=votes.count)
predictions.append(prediction)
return predictions
def predict_proba(self, X):
probas = []
for _ in range(len(X)):
votes = [random.choice(self.classes_) for _ in range(self.n_trees)]
counts = {cls: votes.count(cls) for cls in self.classes_}
probas.append([counts[cls] / self.n_trees for cls in self.classes_])
return probas
if __name__ == "__main__":
X_train = [0.5, 1.2, 2.3, 0.9, 1.8]
y_train = [0, 0, 1, 0, 1]
model = MockRandomForest(n_trees=10, random_state=7)
model.fit(X_train, y_train)
result = model.predict([0.1, 2.0])
print(result)
print(model.predict_proba([0.1, 2.0]))
Output
[0, 1]
[[0.6, 0.4], [0.5, 0.5]]
How it works
This mock class mimics a random forest's ensemble idea by having each 'tree' cast a random vote from the classes seen during training. fit stores the unique classes and their counts, and sets a random seed for reproducibility. predict simulates n_trees independent votes per sample and returns the majority vote using max with a key function. predict_proba converts vote counts into probability estimates by dividing by n_trees. The random seed ensures consistent output across runs, making it useful for testing pipelines before real model integration.
Common mistakes
- Forgetting to call `random.seed` in `__init__` leads to nondeterministic results.
- Assuming `X` is used in prediction—this mock ignores features entirely.
- Not handling cases where `classes_` is empty, causing `random.choice` to fail.
Variations
- Replace random voting with a deterministic rule based on `self._class_counts` for a weighted pattern.
- Add a `feature_importances_` attribute returning zeros to mimic scikit-learn's interface.
Real-world use cases
- Unit-testing ML pipeline code that expects a scikit-learn-compatible estimator without training a real model.
- Generating synthetic predictions for demos or UI mockups before the actual model is deployed.
- Stress-testing downstream consumers (e.g., API endpoints) with fast, variable outputs.
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
- 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
- Detect Concept Drift in Python with a Simple Statistical Test medium
Keep learning
Related tutorials and quizzes for this topic.