Skip to content

API reference

Estimators

optimized_svm.KernelGLMRegressor

Bases: RegressorMixin, _SmoothBase

decision_function(X, offset=None)

Linear predictor on the link scale, including offset.

predict(X, offset=None)

Predicted mean: exp(eta), for the binomial family the proportion expit(eta).

score(X, y, sample_weight=None, offset=None)

Deviance explained D^2 = 1 - deviance(model) / deviance(null model).

The null model is the intercept-only fit to (y, sample_weight, offset): the weighted mean (with offset: the maximum likelihood b with mu_i = g^-1(b + offset_i)).

optimized_svm.OptimizedKernelGLMRegressor

Bases: _OptimizedMixin, KernelGLMRegressor

fit(X, y, sample_weight=None, offset=None, groups=None)

Fits the model; groups is passed to cv.split (splitter objects only).

optimized_svm.OptimizedSVC

Bases: _OptimizedMixin, SmoothSVC

fit(X, y, sample_weight=None, groups=None)

Fits the model; groups is passed to cv.split (splitter objects only).

optimized_svm.OptimizedSVR

Bases: _OptimizedMixin, SmoothSVR

fit(X, y, sample_weight=None, groups=None)

Fits the model; groups is passed to cv.split (splitter objects only).

optimized_svm.SmoothSVC

Bases: ClassifierMixin, _SmoothBase

decision_function(X)

Signed decision values: shape (n,) for two classes (positive values predict classes_[1]), otherwise (n, n_classes) (one-vs-rest).

predict_proba(X)

Class probabilities sigmoid(f(x)) (only for loss="logistic"); for more than two classes the one-vs-rest probabilities are normalised to sum to one.

optimized_svm.SmoothSVR

Bases: RegressorMixin, _SmoothBase

Training

optimized_svm.TrainingProblem

Training problem on (already scaled) features x with an RBF kernel (gamma = 1).

size property

Number of loss terms (= dual variables).

kernel(rows=slice(None), cols=slice(None))

Kernel matrix between loss terms rows and cols.

sample_kernel(rows, cols)

Kernel matrix between the samples rows and cols.

kernel_to(z, rows=slice(None))

Kernel matrix between loss terms rows and new (scaled) points z.

sample_coefficients(a)

Coefficients per sample beta_k = sum_{l: k(l) = k} a_l.

ka(a)

K a / lam per loss term (computed via the sample coefficients).

optimized_svm.train(prob, smo_options=None, newton_options=None, alpha0=None)

Two-step training: SMO warm start followed by Newton refinement.

Indicator losses use a direct constrained QP solver instead (see :mod:optimized_svm.hard). For non-smooth losses (smoothing = 0) the SMO solution is already exact; for losses without SMO formulation (squared, logistic, Poisson) Newton starts at a = 0 with the loss-specific initial bias.

By default the SMO stage stops at the tolerance :data:ROUGH_SMO_TOL or after ROUGH_SMO_STEPS steps per loss term, whichever comes first. Passing tol or max_steps in smo_options replaces these defaults (no step budget then).

optimized_svm.newton(prob, a, b, c, *, tol=1e-12, max_steps=100, max_backtracks=20, sigma=0.0001, beta=0.5, verbose=0)

Damped semismooth Newton method for the (smoothed) primal training problem.

Requires a loss with (piecewise) second derivative. The 1-norm constraint is treated as active iff c > 0 at the starting point.

optimized_svm.Solution dataclass

Solution (a, b, c) of a training problem with ka = K a / lam.

Hard-constraint training

optimized_svm.hard

Exact hard constraints (thesis Sec. 4.1.2 and 4.2.3), for moderate data sets.

The QP is solved in an eigenbasis of the kernel without a regularization jitter. A linear feasibility problem precedes SLSQP; primal feasibility and stationarity are checked afterwards. Lambda is normalized to one during the solve, since it cannot change the primal minimizer.

train_hard(prob)

Minimize the RKHS norm subject to the indicator loss constraints.

Raises ValueError for infeasible constraints and ConvergenceError when a numerical solution cannot be certified. No finite soft-margin penalty is substituted. Tiny kernel eigenvalues below floating-point resolution are discarded; this can make very ill-conditioned problems numerically infeasible. Dense eigendecomposition/SLSQP cost cubic time in n.

Losses

optimized_svm.losses

Loss functions of the training problem, expressed per loss term.

A training problem with n samples consists of m loss terms: one per sample, or two for the epsilon-insensitive loss (one for each side of the tube). Term l belongs to sample kernel_index[l], has weight w_l, label y_l and sign s_l (used by the optional 1-norm constraint, 0 if not applicable). The decision value of a term is f(x_l) + s_l c.

Terms dataclass

Term structure of a training problem.

Loss

Base class: per-term loss phi_l(t) and its derivatives.

param_ratio(name, t, terms)

(d phi'_l / d p) / phi''_l at fixed t for the loss parameter p = name.

Only meaningful for terms with positive curvature; it is the sensitivity of the optimality condition a_l + phi'_l(t_l) = 0 w.r.t. p in units of t and is used by the hypergradient with respect to loss parameters.

initial_bias(terms)

Starting value of the bias for Newton without an SMO warm start (a = 0).

HingeLoss dataclass

Bases: Loss

Smoothed hinge loss w * m_delta(shift - y t) for labels y in {-1, +1}.

LogisticLoss dataclass

Bases: Loss

Logistic loss w * log(1 + exp(-y t)) for y in {-1, +1} (Strasdat, Sec. 4.1.3).

Smooth without a smoothing parameter and strictly convex, but with positive curvature everywhere: the dual solution is dense and the dual is not a separable quadratic, so there is no SMO warm start and every Newton system has the full size n.

EpsilonInsensitiveLoss dataclass

Bases: Loss

Smoothed epsilon-insensitive loss w * (m(y - t - eps) + m(t - y - eps)).

Uses two terms per sample: sign +1 for m(y - t - eps) and -1 for the other side.

SquaredLoss dataclass

Bases: Loss

Least-squares loss w / 2 * (t - y)^2 (LS-SVM).

initial_bias(terms)

Weighted mean of y - offset (the minimiser for a = 0).

PoissonLoss dataclass

Bases: Loss

Poisson negative log-likelihood w * (exp(t) - y t + log(y!)) for counts y.

initial_bias(terms)

log(sum w y / sum w exp(offset)), the minimiser for a = 0 (for all-zero y the numerator is replaced by a small positive mean 1e-3 sum w).

ApproxPoissonLoss dataclass

Bases: Loss

Poisson-type loss with a linear left tail (from the original experiments):

w * (exp(t) - (y + 1) t - 1 + log(y!)) for t > 0 and w * (-y t + log(y!)) else.

It is convex and continuously differentiable; for t <= 0 its curvature vanishes.

BinomialLoss dataclass

Bases: Loss

Binomial half unit deviance with logit link for proportions y in [0, 1].

With mu = expit(t) and w the number of trials (times the sample weight)::

phi = w * (y log(y/mu) + (1 - y) log((1 - y)/(1 - mu)))
    = w * (xlogy(y, y) + xlogy(1 - y, 1 - y) + log(1 + e^t) - y t)

phi' = w (mu - y), phi'' = w mu (1 - mu); the minimum over t is 0 at mu = y.

NegativeBinomialLoss dataclass

Bases: Loss

Negative binomial half unit deviance, log link mu = e^t, dispersion r > 0.

::

phi = w * (y log(y/mu) - (y + r) log((y + r)/(mu + r)))
    = w * (xlogy(y, y) - y t - (y + r) log(y + r) + (y + r) logaddexp(t, log r))

phi' = w r (mu - y)/(mu + r), phi'' = w (y + r) r mu/(mu + r)^2; minimum 0 at mu = y. Variance mu + mu^2 / r; r -> inf approaches the Poisson loss. d phi'/d r = w mu (mu - y)/(mu + r)^2, hence param_ratio = (mu - y)/(r (y + r)).

GammaLoss dataclass

Bases: Loss

Gamma half unit deviance, log link mu = e^t, targets y > 0.

phi = w (y e^{-t} + t - log y - 1), phi' = w (1 - y e^{-t}), phi'' = w y e^{-t}; minimum 0 at mu = y.

TweedieLoss dataclass

Bases: Loss

Tweedie half unit deviance, log link mu = e^t, power 1 < p < 2, targets y >= 0.

::

phi = w * (y^(2-p)/((1-p)(2-p)) - y e^{(1-p)t}/(1-p) + e^{(2-p)t}/(2-p))

phi' = w e^{(1-p)t} (e^t - y), phi'' = w ((p-1) y e^{(1-p)t} + (2-p) e^{(2-p)t}); minimum 0 at mu = y (compound Poisson-gamma; exact zeros allowed).

MaximalMarginLoss dataclass

Bases: Loss

Indicator of y * t >= shift (maximal margin classifier, Sec. 4.1.2).

Positive weights leave the constraint unchanged; zero weights remove it. There are no ordinary first/second derivatives: training and hypergradients use the active constraints.

HardEpsilonInsensitiveLoss dataclass

Bases: Loss

Indicator of abs(t - y) <= epsilon (hard epsilon-SVR, Sec. 4.2.3).

epsilon is a non-negative scalar or one tolerance per sample. Positive weights do not soften the tube; zero weights remove its constraint. Per-sample tolerances are supported by :class:TrainingProblem and sliced automatically in cross-validation.

Hypergradient

optimized_svm.cv_error_and_gradient(theta, x, y, w, folds, loss, validation, blocks=None, max_asum=None, smo_options=None, newton_options=None, warm_start=None, loss_params=(), basis=None, offset=None, n_jobs=None)

Mean validation error over all folds and its gradient w.r.t. theta.

theta = (log lam, log s_1, ..., log s_K, log p_1, ...): regularization, kernel scalings and the values of the loss parameters named in loss_params (fields of loss such as "epsilon" or "smoothing"; they replace the values stored in loss).

warm_start is a list with one (possibly None) start vector per fold; it is updated in place with the new solutions.

With basis (one array of sample indices per fold, indices into x) every fold trains a Subspace SVM whose model is spanned by these basis points (:mod:optimized_svm.subspace); warm_start then holds expansion coefficients instead of dual variables. Loss parameters and the 1-norm constraint are not supported in that case.

n_jobs runs the folds in parallel threads (scikit-learn semantics: None or 1 is serial, -1 uses all cores); the BLAS threads are divided among the workers. The result equals the serial one up to floating-point rounding (the BLAS thread count differs; two parallel runs are bit-identical). Parallel folds pay off most when SMO dominates (classification); for large Newton-dominated problems the serial run already uses multithreaded BLAS, and the memory grows with the number of parallel folds (each holds its kernel and factor matrices).

offset is an optional per-sample offset (like w): it is added to the decision values of the training problem and of the validation predictions. If validation.weighted is set, w[val_idx] is also passed to the validation loss.

optimized_svm.fold_error_and_gradient(x_train, y_train, w_train, x_val, y_val, loss, validation, lam, blocks, max_asum=None, smo_options=None, newton_options=None, alpha0=None, loss_params=(), offset_train=None, w_val=None, offset_val=None)

Validation error of one fold and its gradient w.r.t. (log lam, log s_k, log p_j).

p_j are the loss parameters named in loss_params (e.g. "epsilon", "smoothing"), taken from loss. x_train/x_val must already be scaled. offset_train and offset_val are per-sample offsets added to the decision values (None: zero); w_val are validation weights, passed to validation only if it is weighted.

Multi-class soft-max SVM

optimized_svm.multiclass

Multi-class soft-max SVM: training and hypergradient (Strasdat, Sec. 5.1, Prop. 5.1).

Labels are integers 0, ..., r - 1. The model has one decision function per class,

T = K A / lam + 1 b^T      (n x r),      A in R^{n x r}, b in R^r,

the multi-class analogue of the binary t = K a / lam + b, and minimises

sum_k a_k^T K a_k / (2 lam) + sum_i w_i (logsumexp(T_i) - T_{i, y_i}).

Identifiability. The common class direction is removed with orthonormal Helmert contrasts. Biases are centred; the equivalent hyperparameter-independent gauge penalty rho/2 (1^T b)^2 (rho = mean(w)) is retained in the objective/stationarity API. The canonical representer coefficients satisfy A = -G and hence have zero row sums.

Newton and hypergradient. The stationarity Jacobian is the nonsymmetric matrix

J = [[ I + H M , H E ], [ E^T H M , E^T H E + rho 1 1^T ]],

with M = K / lam and block-diagonal categorical covariances H. It is not factorized directly: use covariance roots H = R R^T in the class contrasts and factor the symmetric positive definite S = I + R^T M R (smallest eigenvalue >= 1), then the small centred-bias Schur complement. The same factors solve the adjoint and produce H (z_a + E z_b) directly. No inverse, eigenvalue truncation or jitter of K is needed; duplicate samples and zero individual sample weights remain supported. The dense system has size n (r - 1) and still costs cubic time.

The factor can be reused for the adjoint if its curvature exactly matches the final iterate. Linear solves check backward residuals in the original stationarity equations. Validation hypergradients are contracted with kernel derivatives as before.

MulticlassProblem

Soft-max training problem on (already scaled) features x with an RBF kernel.

decision(a, b)

(K A / lam, K A / lam + 1 b^T).

gradient(t)

G_ik = w_i (p_ik - [k = y_i]) (derivative of the loss w.r.t. T).

curvature(t)

Per-sample Hessians H_i = w_i (diag p_i - p_i p_i^T), shape (n, r, r).

objective(a, b, ka)

Training objective plus the gauge penalty rho/2 (1^T b)^2.

jacobian(h)

Dense Jacobian J of F w.r.t. (A.ravel(), b) (sample-major ordering).

SoftmaxFactorization dataclass

Covariance-root SPD reduction of the stationarity Jacobian.

With block-diagonal R such that H = R R.T, factor S = I + R.T M R and its small centred-bias Schur complement. No inverse or jitter of the kernel is needed, including with duplicate samples.

solve(rhs_a, rhs_b)

Solve the original, nonsymmetric J d = rhs through SPD systems.

adjoint_curvature(rhs_a, rhs_b)

Return H (z_a + E z_b) for J.T z = rhs without forming J.

MulticlassSolution dataclass

Solution (A, b) of the soft-max problem.

MultinomialNLL dataclass

Multinomial negative log-likelihood sum_v w_v (logsumexp(T_v) - T_{v, y_v}) (summed, not averaged), returning its gradient w.r.t. the decision values T (n_val x r).

A smooth surrogate of the misclassification rate is not provided (use this loss).

initial_bias(y, w, n_classes)

Centred log class frequencies (the exact bias for A = 0 up to centring).

newton_multiclass(prob, a0=None, b0=None, **options)

Damped Newton method for the soft-max problem with warm start (a0, b0).

A failed warm start is repeated from the cold start A = 0, b = initial_bias; a :class:ConvergenceError of the cold start is raised. Classes without any training sample have no finite optimum (b_k -> -inf) and are not supported.

decision_function(x_new, x_train, a, b, lam)

Decision values K(x_new, x_train) A / lam + 1 b^T for scaled features.

predict_proba(x_new, x_train, a, b, lam)

Class probabilities softmax(T) for scaled features.

fold_error_and_gradient_multiclass(x_train, y_train, w_train, x_val, y_val, n_classes, validation, lam, blocks, newton_options=None, warm_start=None, w_val=None)

Validation error of one fold and its gradient w.r.t. (log lam, log s_k).

x_train and x_val must already be scaled; y are integer labels in 0..n_classes-1. warm_start is (A0, b0); w_val is passed to validation only if it is weighted.

cv_error_and_gradient_multiclass(theta, x, y, w, folds, n_classes=None, validation=None, blocks=None, newton_options=None, warm_start=None, n_jobs=None)

Mean validation error over all folds and its gradient w.r.t. theta = (log lam, log s_1, ..., log s_K).

warm_start holds one (possibly None) pair (A, b) per fold and is updated in place. n_classes defaults to max(y) + 1. n_jobs runs the folds in parallel threads (see :func:optimized_svm.hypergradient.run_folds); the result is independent of it up to rounding.

Subspace SVM

optimized_svm.subspace

Subspace SVM: training and hypergradient in a low-dimensional subspace (Strasdat, Sec. 5.3).

The model is restricted to the subspace spanned by m basis points z_1, ..., z_m::

w = sum_j beta_j phi(z_j),    f(x) = sum_j beta_j k(x, z_j) + b.

By Corollary 5.9 the dual of this problem is the standard dual with the projected kernel K_s = K_XZ K_ZZ^{-1} K_ZX (a Nystroem approximation), so a Subspace SVM is an SVM with the explicit finite-dimensional feature map psi(x) = L^{-1} k_Z(x) where K_ZZ = L L^T. The primal problem has only m + 1 unknowns,

min_{u, b}  lam/2 |u|^2 + sum_l phi_l(psi_{k(l)}^T u + b),        beta = L^{-T} u,

and is solved by a damped Newton method with systems of size m + 1 instead of n: cost O(n m^2 + m^3) per step. Losses must have positive curvature somewhere (smoothed hinge or epsilon-insensitive loss with smoothing > 0, squared, logistic, Poisson); SMO is not used.

The hypergradient of the cross-validation error w.r.t. log lam and the log kernel scalings follows from the implicit function theorem for the stationarity conditions in (beta, b); one adjoint system of size m + 1 is solved per fold (derivation in docs/theory/subspace.md).

SubspaceProblem

Training problem on scaled features x restricted to the span of the basis points z (z are scaled, too).

per_sample(f)

Derivatives of the loss w.r.t. the decision values f (summed over the terms of a sample) and the loss value.

SubspaceSolution dataclass

Solution of a subspace problem: expansion coefficients beta w.r.t. the basis points.

choose_basis(n, m, seed=0)

Random subset of m out of n sample indices (sorted).

select_basis(x, lam, tol=1.0, max_size=None)

Greedy pivoted Cholesky of the RBF kernel on scaled features x.

Adds the sample with the largest remaining kernel variance until the absolute trace of the Nystroem residual tr(K - K_s) is at most tol * lam or max_size points are chosen (default max(10, n // 10)). Returns the sorted indices and the final tr(K - K_s) / lam; a value above tol means that the size limit was hit and the subspace model is not a close approximation (the study in benchmarks/subspace_params.py found a cross-validation error at most 1 % above the full model for tol = 1 and at most 14 % for tol = 10).

nystroem_residual(x, idx)

Trace of the Nystroem residual tr(K - K_s) of the RBF kernel on scaled features x for the basis x[idx], i.e. n - ||psi||_F^2 with psi = K_XZ L^-T and L the Cholesky factor of the jittered K_ZZ (as in :class:SubspaceProblem). Clipped at 0.

newton_subspace(prob, beta0=None, b0=None, **options)

Damped Newton method for the subspace problem (m + 1 unknowns).

A warm start (beta0, b0) may lie in a region where the loss is linear in all samples (tiny lam gives huge coefficients), so the Hessian is just lam I and no step is accepted. The solve is then repeated from the cold start u = 0, b = loss.initial_bias, which is always well-posed; a :class:ConvergenceError of the cold start is raised.

fold_error_and_gradient_subspace(x_train, y_train, w_train, z, x_val, y_val, loss, validation, lam, blocks, newton_options=None, beta0=None, offset_train=None, w_val=None, offset_val=None)

Validation error of one fold and its gradient w.r.t. (log lam, log s_k) (subspace model).

x_train, z and x_val must already be scaled. offset_train and offset_val are per-sample offsets added to the decision values; w_val are validation weights, passed to validation only if it is weighted.

Validation losses

optimized_svm.validation

Validation error measures E(f) = sum_v L_v(f_v) for the upper level problem (Sec. 9.1.4).

All measures are differentiable so that the hyperparameter objective has a gradient.

ValidationLoss

Returns the summed loss and its gradient w.r.t. the predictions.

param_grad(name, f, y, w=None)

dE/dp of the summed value at fixed predictions f for the parameter name.

SmoothHingeValidation dataclass

Bases: ValidationLoss

sum_v w_v m_delta(shift - y_v f_v); balanced weights both classes equally.

LogisticValidation dataclass

Bases: ValidationLoss

sum_v w_v log(1 + exp(-y_v f_v)); balanced weights both classes equally.

SmoothAbsoluteValidation dataclass

Bases: ValidationLoss

Smoothed absolute error sum_v m_delta(f_v - y_v) + m_delta(y_v - f_v) (Huber-like).

SquaredValidation dataclass

Bases: ValidationLoss

1/2 sum_v (f_v - y_v)^2.

PoissonValidation dataclass

Bases: ValidationLoss

Poisson deviance-type loss sum_v exp(f_v) - y_v f_v + log(y_v!).

BinomialDeviance dataclass

Bases: ValidationLoss

Binomial half deviance sum_v w_v (y_v log(y_v/mu_v) + (1-y_v) log((1-y_v)/(1-mu_v))).

mu = expit(f), y are proportions and w the numbers of trials.

NegativeBinomialDeviance dataclass

Bases: ValidationLoss

Negative binomial half deviance with log link, see NegativeBinomialLoss.

GammaDeviance dataclass

Bases: ValidationLoss

Gamma half deviance with log link, see GammaLoss.

TweedieDeviance dataclass

Bases: ValidationLoss

Tweedie half deviance with log link, see TweedieLoss.

NegativeBinomialNLL dataclass

Bases: ValidationLoss

Full negative binomial negative log-likelihood with log link mu = e^f::

E = sum_v -lgamma(y+r) + lgamma(r) + lgamma(y+1) - r log(r/(r+mu)) - y log(mu/(r+mu))

Unlike the deviance it contains the terms that depend on the dispersion r and is therefore a proper criterion for tuning r. dE/df = r (mu - y)/(mu + r) and dE/dr = sum -psi(y+r) + psi(r) - log(r/(r+mu)) - 1 + (y+r)/(r+mu).

Kernels and smoothing

optimized_svm.kernels

Gaussian kernel with feature scaling and its derivatives w.r.t. log-scalings.

The hyperparameters of the kernel are scalings s_k > 0 of feature blocks B_k: k(x, z) = exp(-sum_k s_k^2 |x_{B_k} - z_{B_k}|^2). With a single block this is the RBF kernel with gamma = s^2; with one block per feature it is an ARD kernel. The training code works on scaled features x_{B_k} * s_k and an RBF kernel with gamma = 1.

squared_distances(x, z)

Matrix of squared Euclidean distances |x_i - z_j|^2 (clipped at zero).

rbf(x, z)

exp(-|x - z|^2) for already scaled features.

rbf_with_gradient(x, z, blocks=None)

Kernel matrix and its derivatives w.r.t. the log-scalings of all blocks.

Returns K of shape (n, m) and dK of shape (n, m, n_blocks) with dK[..., k] = d K / d log s_k = -2 K * |x_{B_k} - z_{B_k}|^2 (features already scaled).

contract_gradient(x, z, k, left, right, blocks=None)

Bilinear forms left^T (dK / d log s_k) right with dK_k = -2 K * |x_Bk - z_Bk|^2.

k is the kernel matrix between the (already scaled) points x and z. Same as contracting the output of :func:rbf_with_gradient, but without forming the distance matrices of the blocks: with W = K * left right^T one has sum_ij W_ij |x_i - z_j|^2 = rowsum(W) . |x|^2 + colsum(W) . |z|^2 - 2 sum(x * (W z)) per feature, so a single matrix product serves all blocks.

scale_features(x, scaling, blocks=None)

Multiplies the features of each block by its scaling.

optimized_svm.smooth_max

Smooth approximations of the maximum function max(0, t) (Strasdat, Sec. 4.4).

Each approximation m_delta coincides with max(0, t) for |t| >= delta and is a polynomial on (-delta, delta). The degree determines the smoothness:

  • "2": C^1, piecewise quadratic (its conjugate is quadratic, so SMO applies),
  • "3": C^2, piecewise cubic,
  • "6": C^2, a single sextic polynomial on (-delta, delta).

smooth_max(delta, degree='2')

Returns (m, dm, ddm): the smoothed maximum and its first two derivatives.

delta = 0 yields the (non-smooth) maximum itself.