{"record":{"id":"61f13e1538f327e1","repo":"TheAlgorithms/Python","slug":"polynomial-degree-must-be-non-negative","errorCode":null,"errorMessage":"Polynomial degree must be non-negative","messagePattern":"Polynomial degree must be non-negative","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/polynomial_regression.py","lineNumber":49,"sourceCode":"    - https://en.wikipedia.org/wiki/Polynomial_regression\n    - https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse\n    - https://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares\n    - https://en.wikipedia.org/wiki/Singular_value_decomposition\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass PolynomialRegression:\n    __slots__ = \"degree\", \"params\"\n\n    def __init__(self, degree: int) -> None:\n        \"\"\"\n        @raises ValueError: if the polynomial degree is negative\n        \"\"\"\n        if degree < 0:\n            raise ValueError(\"Polynomial degree must be non-negative\")\n\n        self.degree = degree\n        self.params = None\n\n    @staticmethod\n    def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray:\n        \"\"\"\n        Constructs a polynomial regression design matrix for the given input data. For\n        input data x = (x₁, x₂, ..., xₙ) and polynomial degree m, the design matrix is\n        the Vandermonde matrix\n\n            |1  x₁  x₁² ⋯ x₁ᵐ|\n        X = |1  x₂  x₂² ⋯ x₂ᵐ|\n            |⋮  ⋮   ⋮   ⋱ ⋮  |\n            |1  xₙ  xₙ² ⋯  xₙᵐ|\n\n        Reference: https://en.wikipedia.org/wiki/Vandermonde_matrix\n","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/polynomial_regression.py#L31-L67","documentation":"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.","triggerScenarios":"Constructing PolynomialRegression(degree=-1) or any negative integer, often from a hyperparameter search grid or a computed degree expression that evaluates negative.","commonSituations":"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.","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."],"exampleFix":"# before\nmodel = PolynomialRegression(degree=-2)\n\n# after\nmodel = PolynomialRegression(degree=2)","handlingStrategy":"type-guard","validationCode":"degree = int(degree)\nif degree < 0:\n    raise ValueError(f\"degree must be >= 0, got {degree}\")\nmodel = PolynomialRegression(degree)","typeGuard":"def is_valid_degree(degree: int) -> bool:\n    return isinstance(degree, int) and not isinstance(degree, bool) and degree >= 0","tryCatchPattern":null,"preventionTips":["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."],"tags":["machine-learning","regression","polynomial","constructor"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}