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.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 13 views 0 copies

Python code

43 lines
Python 3.9+
import 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

stdout
[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

  1. Replace random voting with a deterministic rule based on `self._class_counts` for a weighted pattern.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from ML engineering pipelines

Related tutorials and quizzes for this topic.