TheAlgorithms/Python · error · ValueError

Polynomial degree must be non-negative

Error message

Polynomial degree must be non-negative

What it means

Thrown by PolynomialRegression.__init__ when degree is negative. A polynomial of negative degree is mathematically undefined, and the Vandermonde design matrix construction (np.vander with N=degree+1) requires degree >= 0.

Source

Thrown at machine_learning/polynomial_regression.py:49

    - https://en.wikipedia.org/wiki/Polynomial_regression
    - https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse
    - https://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
    - https://en.wikipedia.org/wiki/Singular_value_decomposition
"""

import matplotlib.pyplot as plt
import numpy as np


class PolynomialRegression:
    __slots__ = "degree", "params"

    def __init__(self, degree: int) -> None:
        """
        @raises ValueError: if the polynomial degree is negative
        """
        if degree < 0:
            raise ValueError("Polynomial degree must be non-negative")

        self.degree = degree
        self.params = None

    @staticmethod
    def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray:
        """
        Constructs a polynomial regression design matrix for the given input data. For
        input data x = (x₁, x₂, ..., xₙ) and polynomial degree m, the design matrix is
        the Vandermonde matrix

            |1  x₁  x₁² ⋯ x₁ᵐ|
        X = |1  x₂  x₂² ⋯ x₂ᵐ|
            |⋮  ⋮   ⋮   ⋱ ⋮  |
            |1  xₙ  xₙ² ⋯  xₙᵐ|

        Reference: https://en.wikipedia.org/wiki/Vandermonde_matrix

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a non-negative integer degree (0 for a constant fit, 1 for linear, 2 for quadratic, ...).
  2. If degree comes from user input or a config file, validate and clamp it: degree = max(0, int(degree)).
  3. Fix search grids (e.g. range(-1, 5)) that include negative values.

Example fix

# before
model = PolynomialRegression(degree=-2)

# after
model = PolynomialRegression(degree=2)
Defensive patterns

Strategy: type-guard

Validate before calling

degree = int(degree)
if degree < 0:
    raise ValueError(f"degree must be >= 0, got {degree}")
model = PolynomialRegression(degree)

Type guard

def is_valid_degree(degree: int) -> bool:
    return isinstance(degree, int) and not isinstance(degree, bool) and degree >= 0

Prevention

When it happens

Trigger: Constructing PolynomialRegression(degree=-1) or any negative integer, often from a hyperparameter search grid or a computed degree expression that evaluates negative.

Common situations: Hyperparameter grids that include negative degrees; degree computed from data (e.g. len(features) - 5) going negative on small inputs; config typos or unvalidated CLI arguments parsed as integers.

Related errors


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