TheAlgorithms/Python · error · ValueError
gamma must be float or int
Error message
gamma must be float or int
What it means
Raised by the SupportVectorMachine constructor when gamma for the rbf kernel is not a float or int. Note that with the annotated default gamma: float = 0.0 this branch is effectively a defensive type check: only exotic objects (strings, None, numpy scalars that are not Python numbers) reach it, and Python bool passes because bool subclasses int.
Source
Thrown at machine_learning/support_vector_machines.py:69
ValueError: gamma must be > 0
"""
def __init__(
self,
*,
regularization: float = np.inf,
kernel: str = "linear",
gamma: float = 0.0,
) -> None:
self.regularization = regularization
self.gamma = gamma
if kernel == "linear":
self.kernel = self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma, (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
self.kernel = self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
msg = f"Unknown kernel: {kernel}"
raise ValueError(msg)
# kernels
def __linear(self, vector1: ndarray, vector2: ndarray) -> float:
"""Linear kernel (as if no kernel used at all)"""
return np.dot(vector1, vector2)
def __rbf(self, vector1: ndarray, vector2: ndarray) -> float:
"""
RBF: Radial Basis Function KernelView on GitHub (pinned to f5988cc097)
Solutions
- Convert the config value to float before passing: gamma=float(cfg['gamma']).
- Do not use None or 'auto' sentinels; this API requires a concrete number.
- Validate config at load time with a numeric check (isinstance(value, (int, float)) and not isinstance(value, bool)).
Example fix
# before svm = SupportVectorMachine(kernel='rbf', gamma=cfg['gamma']) # cfg value is '0.5' # after gamma = float(cfg['gamma']) svm = SupportVectorMachine(kernel='rbf', gamma=gamma)
Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(gamma, (int, float)) or isinstance(gamma, bool):
gamma = float(gamma) # or raise your own error
svm = SupportVectorMachine(kernel='rbf', gamma=gamma) Type guard
def is_numeric_gamma(value) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool) Prevention
- Convert config-sourced values with float() at load time.
- Never pass None or 'auto' as gamma to this API.
When it happens
Trigger: Passing kernel='rbf' with gamma as a string ('auto'), None, or a non-numeric object. Python True/False bypass this check since bool is an int subclass; np.float64 also passes as it registers as a float-like via isinstance in most builds or is caught here depending on version.
Common situations: Forwarding unvalidated config values (from JSON/CLI) straight into the constructor, e.g. gamma='0.5' parsed as a string; or passing gamma=None as a 'use default' sentinel, which this API does not support.
Related errors
- Unknown kernel: {kernel}
- Length of predicted and actual array must be same.
- y_true can have values -1 or 1 only.
- Test samples' feature length does not equal to that of train
- gamma value must be non-negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/5f97212995ed3ddc.
Report an issue: GitHub.