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
- Pass a non-negative integer degree (0 for a constant fit, 1 for linear, 2 for quadratic, ...).
- If degree comes from user input or a config file, validate and clamp it: degree = max(0, int(degree)).
- 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
- Validate config-sourced hyperparameters at load time.
- Start search grids at 0 or 1, never negative values.
- Cast to int explicitly to reject floats like 2.5 early.
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
- Data must have dimensions N x 1
- Design matrix is not full rank, can't compute coefficients
- Predictor hasn't been fit yet
- The number of coefficients should be equal to the degree + 1
- Either arr or size must be specified
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/61f13e1538f327e1.
Report an issue: GitHub.