deepbox/ml
Support Vector Machines
Kernel, linear, nu-formulation and one-class support vector models.
- SVM
Overview
SVCandSVRdefault to therbfkernel withgamma: "scale"andC: 1.0, as scikit-learn does. They solve the dual problem with SMO and cache kernel rows (200 MB by default), so training cost grows faster than linearly with the number of samples. For large linear problems useLinearSVCorLinearSVR.- Two defaults differ from scikit-learn:
LinearSVCusesloss: "hinge"(scikit-learn: squared hinge), andLinearSVRusesepsilon: 0.1(scikit-learn: 0). OneClassSVMreturns 1 for inliers and -1 for outliers. Since 1.5.0,nucontrols the share of training outliers correctly: withnu = 0.1about 10 percent of the training rows are flagged, where 1.0.0 flagged 88 percent.- Support vector machines are sensitive to feature scale. Standardize features first, for example with
StandardScaler.
ClassWeightOption
typePer-class penalty multipliers: "balanced" or a map from class label to weight.
type ClassWeightOption = "balanced" | Record<number, number>;GammaOption
typeKernel coefficient: a positive number, "scale" (1 / (n_features * X.var())) or "auto" (1 / n_features).
type GammaOption = number | "scale" | "auto";KernelType
typeKernel functions supported by the kernel SVM estimators.
type KernelType = "rbf" | "linear" | "poly" | "sigmoid";LinearSVCLoss
typeLoss of LinearSVC: "hinge" or "squaredHinge".
type LinearSVCLoss = "hinge" | "squaredHinge";LinearSVCOptions
typeConstructor options of LinearSVC.
readonly C?: numberPenalty of margin violations, must be positive (default: 1.0).
readonly loss?: LinearSVCLossLoss function (default: "hinge").
readonly fitIntercept?: booleanFit an intercept (default: true).
readonly interceptScaling?: numberValue of the constant feature that carries the intercept (default: 1).
readonly maxIter?: numberMaximum number of passes over the data (default: 1000).
readonly tol?: numberStopping tolerance on the projected-gradient range (default: 1e-4).
readonly classWeight?: ClassWeightOptionPer-class multiplier of
C: "balanced" or a map from class label to weight.readonly randomState?: numberSeed of the coordinate order.
LinearSVRLoss
typeLoss of LinearSVR: "epsilonInsensitive" or "squaredEpsilonInsensitive".
type LinearSVRLoss = "epsilonInsensitive" | "squaredEpsilonInsensitive";LinearSVROptions
typeConstructor options of LinearSVR.
readonly C?: numberPenalty of errors outside the epsilon tube, must be positive (default: 1.0).
readonly epsilon?: numberHalf-width of the tube in which errors are not penalized (default: 0.1).
readonly loss?: LinearSVRLossLoss function (default: "epsilonInsensitive").
readonly fitIntercept?: booleanFit an intercept (default: true).
readonly interceptScaling?: numberValue of the constant feature that carries the intercept (default: 1).
readonly maxIter?: numberMaximum number of passes over the data (default: 1000).
readonly tol?: numberStopping tolerance relative to the violation of the first pass (default: 1e-4).
readonly randomState?: numberSeed of the coordinate order.
NuSVCOptions
typeConstructor options of NuSVC.
readonly nu?: numberUpper bound on the fraction of margin errors and lower bound on the fraction of support vectors, in (0, 1] (default: 0.5).
readonly kernel?: KernelTypeKernel function (default: "rbf").
readonly gamma?: GammaOptionKernel coefficient of
rbf,polyandsigmoid(default: "scale").readonly coef0?: numberIndependent term of the
polyandsigmoidkernels (default: 0).readonly degree?: numberDegree of the
polykernel, an integer >= 1 (default: 3).readonly maxIter?: numberBudget of SMO updates, expressed as passes over the data: the solver stops after at most
maxIter * nworking-set updates per binary problem (default: 1000).readonly tol?: numberStopping tolerance on the maximal KKT violation (default: 1e-3).
readonly cacheSize?: numberSize of the kernel row cache in megabytes (default: 200).
NuSVROptions
typeConstructor options of NuSVR.
readonly nu?: numberUpper bound on the fraction of training errors and lower bound on the fraction of support vectors, in (0, 1] (default: 0.5).
readonly C?: numberPenalty of errors, must be positive (default: 1.0).
readonly kernel?: KernelTypeKernel function (default: "rbf").
readonly gamma?: GammaOptionKernel coefficient of
rbf,polyandsigmoid(default: "scale").readonly coef0?: numberIndependent term of the
polyandsigmoidkernels (default: 0).readonly degree?: numberDegree of the
polykernel, an integer >= 1 (default: 3).readonly maxIter?: numberBudget of SMO updates in passes over the 2 * n dual variables (default: 1000).
readonly tol?: numberStopping tolerance on the maximal KKT violation (default: 1e-3).
readonly cacheSize?: numberSize of the kernel row cache in megabytes (default: 200).
OneClassSVMOptions
typeConstructor options of OneClassSVM.
type OneClassSVMOptions = NuSVCOptions;SVCOptions
typeConstructor options of SVC.
readonly C?: numberPenalty of margin violations, must be positive (default: 1.0).
readonly kernel?: KernelTypeKernel function (default: "rbf").
readonly gamma?: GammaOptionKernel coefficient of
rbf,polyandsigmoid(default: "scale").readonly coef0?: numberIndependent term of the
polyandsigmoidkernels (default: 0).readonly degree?: numberDegree of the
polykernel, an integer >= 1 (default: 3).readonly maxIter?: numberBudget of SMO updates, expressed as passes over the data: the solver stops after at most
maxIter * nworking-set updates per binary problem (default: 1000).readonly tol?: numberStopping tolerance on the maximal KKT violation (default: 1e-3).
readonly classWeight?: ClassWeightOptionPer-class multiplier of
C: "balanced" or a map from class label to weight.readonly cacheSize?: numberSize of the kernel row cache in megabytes (default: 200).
SVROptions
typeConstructor options of SVR.
readonly C?: numberPenalty of errors outside the epsilon tube, must be positive (default: 1.0).
readonly kernel?: KernelTypeKernel function (default: "rbf").
readonly gamma?: GammaOptionKernel coefficient of
rbf,polyandsigmoid(default: "scale").readonly coef0?: numberIndependent term of the
polyandsigmoidkernels (default: 0).readonly degree?: numberDegree of the
polykernel, an integer >= 1 (default: 3).readonly epsilon?: numberHalf-width of the tube in which errors are not penalized (default: 0.1).
readonly maxIter?: numberBudget of SMO updates in passes over the 2 * n dual variables (default: 1000).
readonly tol?: numberStopping tolerance on the maximal KKT violation (default: 1e-3).
readonly cacheSize?: numberSize of the kernel row cache in megabytes (default: 200).
LinearSVC
Support Vector Machine classifier with a linear kernel.
Minimizes 0.5 ||w||^2 + C * sum_i loss(y_i, w.x_i + b) with dual coordinate descent (the LIBLINEAR algorithm). More than two classes are handled one-vs-rest.
predictProba returns a monotone squashing of the decision values, not calibrated probabilities.
import { LinearSVC } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [2, 3], [3, 1], [4, 2]]);const y = tensor([0, 0, 1, 1]); const svm = new LinearSVC({ C: 1.0 });svm.fit(X, y);const predictions = svm.predict(X);Members (13)
constructor(options?: LinearSVCOptions)classes: Tensor | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.coef: TensorWeight vectors, shape (1, n_features) for two classes (positive means
classes[1]) and (n_classes, n_features) otherwise.intercept: TensorIntercepts, shape (1,) for two classes and (n_classes,) otherwise.
nIter: numberNumber of passes over the data used by the slowest binary problem.
fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisFit the classifier.
predict(X: Tensor): TensorPredict class labels.
decisionFunction(X: Tensor): TensorSigned distances
X @ coef.T + interceptto the separating hyperplanes.predictProba(X: Tensor): TensorClass scores squashed into rows that sum to one: the logistic function of the decision value for two classes, the per-class logistic values normalized to sum to one otherwise.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>Get hyperparameters, including
classWeightandrandomStateonly when set.setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): LinearSVCCreate an unfitted copy with the same hyperparameters.
LinearSVR
Support Vector Regression with a linear kernel.
Minimizes 0.5 ||w||^2 + C * sum_i loss(|y_i - w.x_i - b| - epsilon) with dual coordinate descent (the LIBLINEAR algorithm).
import { LinearSVR } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4]]);const y = tensor([1.5, 2.5, 3.5, 4.5]); const svr = new LinearSVR({ C: 1.0, epsilon: 0.1 });svr.fit(X, y);const predictions = svr.predict(X);Members (10)
constructor(options?: LinearSVROptions)coef: TensorWeight vector, shape (n_features,).
intercept: TensorIntercept, shape (1,).
nIter: numberNumber of passes over the data used by the last fit.
fit(X: Tensor, y: Tensor): thisFit the regressor.
predict(X: Tensor): TensorPredict target values.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>Get hyperparameters, including
randomStateonly when set.setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): LinearSVRCreate an unfitted copy with the same hyperparameters.
NuSVC
Nu-Support Vector Classification.
Like SVC but nu in (0, 1] replaces C: it is an upper bound on the fraction of margin errors and a lower bound on the fraction of support vectors. More than two classes are handled with one-vs-one voting.
predictProba returns a monotone squashing of the decision values, not calibrated probabilities.
import { NuSVC } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [1, 1], [1, 0], [0, 1]]);const y = tensor([0, 0, 1, 1]); const clf = new NuSVC({ nu: 0.5 });clf.fit(X, y);const predictions = clf.predict(X);Members (15)
constructor(options?: NuSVCOptions)classes: Tensor | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.supportVectors: TensorSupport vectors, shape (n_SV, n_features), grouped by class.
supportIndices: TensorIndices of the support vectors in the training data, shape (n_SV,), dtype int32.
nSupport: TensorNumber of support vectors of each class, shape (n_classes,), dtype int32.
dualCoef: TensorDual coefficients
alpha_i * y_i, shape (n_classes - 1, n_SV), scikit-learn layout.intercept: TensorDecision-function offsets, one per class pair, scikit-learn sign convention.
fit(X: Tensor, y: Tensor): thisFit the classifier.
predict(X: Tensor): TensorPredict class labels by one-vs-one voting.
decisionFunction(X: Tensor): TensorSigned decision values.
predictProba(X: Tensor): TensorClass scores squashed into rows that sum to one.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>Get hyperparameters.
setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): NuSVCCreate an unfitted copy with the same hyperparameters.
NuSVR
Nu-Support Vector Regression.
Like SVR but nu in (0, 1] controls the fraction of support vectors and the width of the insensitive tube is found by the solver instead of being given.
import { NuSVR } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1.2, 2.1, 2.9, 4.0, 5.1]); const svr = new NuSVR({ nu: 0.5 });svr.fit(X, y);const predictions = svr.predict(X);Members (11)
constructor(options?: NuSVROptions)supportVectors: TensorSupport vectors, shape (n_SV, n_features).
supportIndices: TensorIndices of the support vectors in the training data, shape (n_SV,), dtype int32.
dualCoef: TensorDual coefficients
alpha_i - alpha_i*, shape (1, n_SV).intercept: TensorIntercept of the decision function, shape (1,).
fit(X: Tensor, y: Tensor): thisFit the regressor.
predict(X: Tensor): TensorPredict target values.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>Get hyperparameters.
setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): NuSVRCreate an unfitted copy with the same hyperparameters.
OneClassSVM
One-Class SVM for unsupervised outlier detection.
Learns a boundary that separates the data from the origin in kernel feature space (Scholkopf et al.). nu in (0, 1] bounds the fraction of training errors from above and the fraction of support vectors from below.
scoreSamples returns the raw kernel expansion sum_i alpha_i K(sv_i, x), decisionFunction returns scoreSamples(X) - offset, and predict returns +1 where the decision function is >= 0 and -1 elsewhere.
import { OneClassSVM } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 1], [1, 2], [2, 1], [2, 2], [10, 10]]); const ocsvm = new OneClassSVM({ nu: 0.2 });ocsvm.fit(X);const labels = ocsvm.predict(X); // +1 inlier, -1 outlierMembers (13)
constructor(options?: OneClassSVMOptions)offset: numberDecision threshold in
scoreSamplesunits: samples scoring below it are outliers.supportVectors: TensorSupport vectors, shape (n_SV, n_features).
supportIndices: TensorIndices of the support vectors in the training data, shape (n_SV,), dtype int32.
dualCoef: TensorDual coefficients
alpha_i(sum tonu * n_samples), shape (1, n_SV).fit(X: Tensor, _y?: Tensor): thisFit the detector on inlier-dominated data.
predict(X: Tensor): TensorPredict whether samples are inliers.
fitPredict(X: Tensor, _y?: Tensor): TensorFit on
X, then predict labels for the same samples.scoreSamples(X: Tensor): TensorRaw scores
sum_i alpha_i K(sv_i, x): lower values are more abnormal.decisionFunction(X: Tensor): TensorSigned distance to the decision boundary,
scoreSamples(X) - offset: negative values are outliers.getParams(): Record<string, unknown>Get hyperparameters.
setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): OneClassSVMCreate an unfitted copy with the same hyperparameters.
SVC
Support Vector Classification with the kernel trick.
Solves the C-SVC dual with the LIBSVM working-set SMO algorithm and handles more than two classes with one-vs-one voting, like scikit-learn's SVC. Supports RBF, polynomial, sigmoid and linear kernels.
predictProba returns a monotone squashing of the decision values, not calibrated probabilities. Wrap the classifier in CalibratedClassifierCV when calibrated probabilities matter.
import { SVC } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [1, 1], [1, 0], [0, 1]]);const y = tensor([0, 0, 1, 1]); const svc = new SVC({ kernel: 'rbf', C: 1.0 });svc.fit(X, y);const predictions = svc.predict(X);Members (16)
constructor(options?: SVCOptions)classes: Tensor | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.supportVectors: TensorSupport vectors, shape (n_SV, n_features), grouped by class.
supportIndices: TensorIndices of the support vectors in the training data, shape (n_SV,), dtype int32.
nSupport: TensorNumber of support vectors of each class, shape (n_classes,), dtype int32.
dualCoef: TensorDual coefficients
alpha_i * y_i, shape (n_classes - 1, n_SV), scikit-learn layout.intercept: TensorDecision-function offsets, one per class pair, scikit-learn sign convention.
nIter: numberLargest number of SMO updates used by any binary sub-problem.
fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisFit the classifier.
predict(X: Tensor): TensorPredict class labels by one-vs-one voting.
decisionFunction(X: Tensor): TensorSigned decision values.
predictProba(X: Tensor): TensorClass scores squashed into rows that sum to one: the logistic function of the decision value for two classes, a softmax of the one-vs-rest scores otherwise.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>Get hyperparameters, including
classWeightonly when it is set.setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): SVCCreate an unfitted copy with the same hyperparameters.
SVR
Epsilon-Support Vector Regression with the kernel trick.
Solves the epsilon-SVR dual with the LIBSVM working-set SMO algorithm, so the result agrees with scikit-learn's SVR up to the solver tolerance. Supports RBF, polynomial, sigmoid and linear kernels.
import { SVR } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1.2, 2.1, 2.9, 4.0, 5.1]); const svr = new SVR({ kernel: 'rbf', C: 10 });svr.fit(X, y);const predictions = svr.predict(X);Members (11)
constructor(options?: SVROptions)supportVectors: TensorSupport vectors, shape (n_SV, n_features).
supportIndices: TensorIndices of the support vectors in the training data, shape (n_SV,), dtype int32.
dualCoef: TensorDual coefficients
alpha_i - alpha_i*, shape (1, n_SV).intercept: TensorIntercept of the decision function, shape (1,).
fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisFit the regressor.
predict(X: Tensor): TensorPredict target values.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>Get hyperparameters.
setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): SVRCreate an unfitted copy with the same hyperparameters.
import { LinearSVC, OneClassSVM, SVC, SVR } from "deepbox/ml";import { tensor } from "deepbox/ndarray"; const X = tensor([[1, 2], [2, 1], [3, 3], [4, 4]]);const y = tensor([0, 0, 1, 1]); console.log(new LinearSVC().fit(X, y).predict(X).toString());console.log(new SVC({ kernel: "rbf", C: 1 }).fit(X, y).predict(X).toString());console.log(new SVR({ kernel: "rbf" }).fit(X, tensor([1, 1.5, 3, 4])).predict(X).toString());console.log(new OneClassSVM({ nu: 0.25 }).fit(X).predict(X).toString()); // 1 inlier, -1 outlierFound a mistake? Open an issue.