{"record":{"id":"8a4bf33995d5c83e","repo":"TheAlgorithms/Python","slug":"gamma-value-must-be-non-negative","errorCode":null,"errorMessage":"gamma value must be non-negative","messagePattern":"gamma value must be non-negative","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/sequential_minimum_optimization.py","lineNumber":424,"sourceCode":"        self.degree = np.float64(degree)\n        self.coef0 = np.float64(coef0)\n        self.gamma = np.float64(gamma)\n        self._kernel_name = kernel\n        self._kernel = self._get_kernel(kernel_name=kernel)\n        self._check()\n\n    def _polynomial(self, v1, v2):\n        return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree\n\n    def _linear(self, v1, v2):\n        return np.inner(v1, v2) + self.coef0\n\n    def _rbf(self, v1, v2):\n        return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2))\n\n    def _check(self):\n        if self._kernel == self._rbf and self.gamma < 0:\n            raise ValueError(\"gamma value must be non-negative\")\n\n    def _get_kernel(self, kernel_name):\n        maps = {\"linear\": self._linear, \"poly\": self._polynomial, \"rbf\": self._rbf}\n        return maps[kernel_name]\n\n    def __call__(self, v1, v2):\n        return self._kernel(v1, v2)\n\n    def __repr__(self):\n        return self._kernel_name\n\n\ndef count_time(func):\n    def call_func(*args, **kwargs):\n        import time\n\n        start_time = time.time()\n        func(*args, **kwargs)","sourceCodeStart":406,"sourceCodeEnd":442,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/sequential_minimum_optimization.py#L406-L442","documentation":"Raised by the kernel helper class inside sequential_minimum_optimization.py when the RBF kernel is selected with a negative gamma. _check() runs during setup and validates that the RBF width parameter is non-negative, because a negative gamma would produce an exploding (non-decaying) exponential kernel that is mathematically invalid for RBF.","triggerScenarios":"Constructing the SMO classifier (or its kernel object) with kernel='rbf' and a gamma value less than 0. Other kernels (linear, poly) never trigger this check even with negative gamma.","commonSituations":"Typosigning gamma (e.g. gamma=-0.1 instead of 0.1), copying hyperparameters from a convention where gamma means inverse width (1/(2*sigma^2)) and mixing up signs, or sweeping gamma over a log range that includes negatives.","solutions":["Set gamma to a non-negative value; typical starting points are 1/n_features or values from a logspace grid like 0.001-10.","If you intended gamma = 1/(2*sigma^2), compute it explicitly so the result is positive.","Switch to kernel='linear' if you do not need the RBF kernel at all."],"exampleFix":"# before\nmodel = SMO(train_samples, train_labels, kernel='rbf', gamma=-0.5)\n\n# after\nmodel = SMO(train_samples, train_labels, kernel='rbf', gamma=0.5)","handlingStrategy":"validation","validationCode":"gamma = 1.0 / train_samples.shape[1]  # positive default\nassert gamma >= 0, 'gamma must be non-negative for rbf'","typeGuard":"def is_valid_gamma(g) -> bool:\n    return isinstance(g, (int, float)) and not isinstance(g, bool) and g >= 0","tryCatchPattern":null,"preventionTips":["Generate gamma candidates from np.logspace, which never yields negatives.","Centralize kernel hyperparameters in one validated config object.","Keep sign conventions written next to the config keys."],"tags":["machine-learning","svm","kernel","hyperparameters"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}