TheAlgorithms/Python · error · ValueError

Decision tree not yet trained

Error message

Decision tree not yet trained

What it means

Raised by DecisionTree.predict on a tree whose self.prediction is None and which has neither a left nor a right subtree. That state means train() never ran (or never reached a leaf assignment), so there is no decision boundary or leaf value to predict with.

Source

Thrown at machine_learning/decision_tree.py:155

        return

    def predict(self, x):
        """
        predict:
        @param x: a floating point value to predict the label of
        the prediction function works by recursively calling the predict function
        of the appropriate subtrees based on the tree's decision boundary
        """
        if self.prediction is not None:
            return self.prediction
        elif self.left is not None and self.right is not None:
            if x >= self.decision_boundary:
                return self.right.predict(x)
            else:
                return self.left.predict(x)
        else:
            raise ValueError("Decision tree not yet trained")


class TestDecisionTree:
    """Decision Tres test class"""

    @staticmethod
    def helper_mean_squared_error_test(labels, prediction):
        """
        helper_mean_squared_error_test:
        @param labels: a one dimensional numpy array
        @param prediction: a floating point value
        return value: helper_mean_squared_error_test calculates the mean squared error
        """
        squared_error_sum = float(0)
        for label in labels:
            squared_error_sum += (label - prediction) ** 2

        return float(squared_error_sum / labels.size)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Call train(x, y) on the root tree before any predict().
  2. Track trained state in your own code (e.g. a fitted flag) and train lazily on first predict.
  3. If the error persists after training, verify you are calling predict on the same root object you trained, not a fresh instance.

Example fix

# before
dt = DecisionTree()
dt.predict(3.0)

# after
dt = DecisionTree()
dt.train(x_train, y_train)
dt.predict(3.0)
Defensive patterns

Strategy: validation

Validate before calling

if dt.prediction is None and dt.left is None:
    dt.train(x_train, y_train)
dt.predict(3.0)

Type guard

def is_trained(tree) -> bool:
    return tree.prediction is not None or (tree.left is not None and tree.right is not None)

Try / catch

try:
    dt.predict(x)
except ValueError as e:
    if "not yet trained" in str(e):
        dt.train(x_train, y_train)
        return dt.predict(x)
    raise

Prevention

When it happens

Trigger: Creating dt = DecisionTree() and calling dt.predict(5.0) before any dt.train(x, y) call; also reachable if train exited early without setting self.prediction due to a subclass override.

Common situations: Forgetting to train in a script that loads a preprocessed dataset, reusing a tree object after resetting fields, or control flow that skips the training branch when a cache miss happens.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/fbe9f674f32534f9. Report an issue: GitHub.