mojolearn.svm#

Support vector machines.

SVC and SVR are kernel machines trained by SMO. LinearSVC and LinearSVR are linear machines trained by the quasi-Newton solver of LogisticRegression (L-BFGS, or OWL-QN for an l1 penalty) on the hinge family of losses. The linear machines minimize:

mean_i loss(y_i, x_i @ w + b) + penalty(w) / (C * n_samples)

where penalty is the l1 norm or half the squared l2 norm: scikit-learn’s LinearSVC / LinearSVR objective divided by C * n_samples. The intercept is never penalized. tol is the gradient tolerance; the objective-change tolerance is 0.1 * tol. This follows cuML’s LinearSVC and LinearSVR.

Classes

SVC(*[, C, kernel, degree, gamma, coef0, ...])

C-support vector classification.

SVR(*[, kernel, degree, gamma, coef0, tol, ...])

Epsilon-support vector regression.

LinearSVC(*[, penalty, loss, C, ...])

Linear support vector classification.

LinearSVR(*[, epsilon, penalty, loss, C, ...])

Linear support vector regression.

class mojolearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, tol=0.001, cache_size=1024.0, max_iter=-1, nochange_steps=1000, verbose=False, output_type=None, random_state=None, class_weight=None, decision_function_shape='ovo', probability=False, break_ties=False)[source]#

Bases: NumericModeMixin

C-support vector classification.

Follows scikit-learn’s SVC, with cuML’s SVC as the reference implementation: an SMO solver with the kernel matrices computed on the GPU. Two classes train one machine; more train one machine per class pair (one-vs-one, libsvm’s scheme) and predict by vote, ties going to the lowest class. X is converted to float32 (sparse input is densified), and non-finite values in X raise an error naming the first bad cell. Supports the 'identical' (default) and 'fast' numeric modes; 'fast' is available on Apple GPUs only.

Defaults that differ from scikit-learn: gamma='auto' (scikit-learn uses ‘scale’); decision_function_shape='ovo' (scikit-learn uses ‘ovr’); cache_size is the prediction buffer in MiB and does not affect training. There is no shrinking parameter. Every parameter is keyword-only. A parameter that would be ignored is refused rather than accepted: degree with any kernel but ‘poly’, coef0 with any kernel but ‘poly’ or ‘sigmoid’, random_state without probability=True, and a truthy verbose or any output_type all raise NotImplementedError.

Parameters:
  • C (float, default 1.0) – Regularization penalty. Must be finite and positive.

  • kernel ({‘linear’, ‘rbf’, ‘poly’, ‘sigmoid’, ‘precomputed’}, default ‘rbf’) – The kernel. ‘poly’ is (gamma * <x, y> + coef0) ** degree; ‘sigmoid’ is tanh(gamma * <x, y> + coef0). With ‘precomputed’, X is the n x n kernel matrix at fit and the q x n kernel against the training rows at predict; support_vectors_ then holds the support rows of the kernel matrix (scikit-learn’s is empty). Other names, including ‘polynomial’ and ‘tanh’, raise.

  • degree (int, default 3) – Degree of the ‘poly’ kernel, an integer in [0, 32]. Must stay 3 with any other kernel.

  • gamma (float, ‘auto’ or ‘scale’, default ‘auto’) – Kernel coefficient, a finite float >= 0. ‘auto’ is 1 / n_features; ‘scale’ is 1 / (n_features * X.var()), computed from the exact variance of the float32 data, so it can differ from scikit-learn’s float32 X.var() in the last bits.

  • coef0 (float, default 0.0) – Independent term of the ‘poly’ and ‘sigmoid’ kernels, finite. Must stay 0.0 with any other kernel.

  • tol (float, default 1e-3) – Stopping tolerance. Must be finite and positive.

  • cache_size (float, default 1024.0) – Size in MiB of the kernel tile buffer used at prediction, which sets the prediction batch size; results do not depend on it. It has no training-time kernel cache role here. Must be positive and finite.

  • max_iter (int, default -1) – Cap on the total inner SMO iterations (cuML’s meaning); -1 means no limit. 0 and values below -1 are refused.

  • nochange_steps (int, default 1000) – Follows cuML’s nochange_steps convergence rule. Must be >= 0.

  • verbose (bool, default False) – Only False is accepted; this estimator prints no log lines.

  • output_type (None, default None) – Only None is accepted; results are mojolearn Arrays.

  • random_state (int or None, default None) – With probability=True, the seed of the cross-validation fold shuffle (None means 0); an int in [0, 2**64). Refused otherwise.

  • class_weight (dict, ‘balanced’ or None, default None) – Per-class weights; row i’s penalty becomes C * class_weight[y_i] * sample_weight_i.

  • decision_function_shape ({‘ovo’, ‘ovr’}, default ‘ovo’) – With more than two classes, decision_function returns the pairwise (n, K(K-1)/2) form (‘ovo’) or scikit-learn’s voted (n, K) form (‘ovr’). No effect with two classes.

  • probability (bool, default False) – Fit Platt scaling (libsvm’s method: a seeded 5-fold cross-validation per class pair, then a sigmoid fit and, for more than two classes, pairwise coupling) so that predict_proba and predict_log_proba are available. The fold shuffle differs from libsvm’s, so the probabilities are not bit-equal to libsvm’s.

  • break_ties (bool, default False) – With decision_function_shape='ovr' and more than two classes, predict the argmax of the ‘ovr’ decision function instead of the vote. Must be False with ‘ovo’ (scikit-learn’s rule).

  • numeric_mode ({‘identical’, ‘fast’} or None, default None) – Numeric mode for this estimator; None uses the process default.

Variables:
  • classes_ (list of shape (K,)) – The distinct labels, sorted ascending, as Python scalars. classes_[1] is the positive class of the binary decision function.

  • support_ (Array of shape (n_SV,), int32) – Indices of the support vectors in the training data.

  • support_vectors_ (Array of shape (n_SV, n_features), float32) – The support vectors.

  • dual_coef_ (Array of shape (1, n_SV) or (K - 1, n_SV), float32) – Dual coefficients, in scikit-learn’s layout.

  • intercept_ (Array of shape (1,) or (K(K-1)/2,), float32) – Intercepts of the decision functions.

  • coef_ (Array of shape (1, n_features) or (K(K-1)/2, n_features), float32) – Primal weights dual_coef_ @ support_vectors_, only for kernel='linear'; raises AttributeError otherwise, as scikit-learn does.

  • n_support_ (int, or Array of shape (K,), int32) – Number of support vectors. With two classes this is a single count (cuML’s form; scikit-learn returns a per-class array); with more, the per-class counts.

  • n_iter_ (int, or Array of shape (K(K-1)/2,), int32) – Total inner SMO iterations, per class pair with more than two classes.

  • probB_ (probA_,) – Platt sigmoid parameters per class pair, when probability=True.

  • n_features_in_ (int) – Number of features seen during fit.

Notes

With more than two classes the fitted arrays follow scikit-learn’s layout and orientation: a pair’s decision is positive toward its lower class, support_ is grouped by class (ascending within a class), dual_coef_ is (K - 1, n_SV) and intercept_ is (K(K-1)/2,).

predict returns an int64 or float64 Array for integer or float labels, and a Python list for other label types.

Examples

>>> import numpy as np, mojolearn
>>> rng = np.random.default_rng(0)
>>> X = rng.random((1000, 8), dtype=np.float32)
>>> y = (X[:, 0] + X[:, 1] > 1.0).astype(np.int64)
>>> model = mojolearn.SVC(C=1.0, kernel="rbf").fit(X, y)
>>> labels = model.predict(X[:5])
fit(X, y, sample_weight=None)[source]#

Fit the support vector classifier.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data, converted to float32. With kernel='precomputed', the square n x n kernel matrix.

  • y (array-like of shape (n_samples,)) – Class labels; two or more distinct values.

  • sample_weight (array-like of shape (n_samples,), default None) – Per-sample weights; row i’s penalty becomes C * w_i (times its class weight). None weights every sample equally.

Returns:

self (SVC) – The fitted estimator.

property coef_#

Primal weights, only for kernel='linear'.

Shape (1, n_features) for two classes and (K(K-1)/2, n_features) for K > 2 classes, float32. Raises AttributeError for other kernels or before fit.

decision_function(X)[source]#

Evaluate the decision function for the rows of X.

Parameters:

X (array-like of shape (n_rows, n_features)) – Query data. With kernel='precomputed', the kernel between the queries and the training rows, shape (n_rows, n_samples).

Returns:

Array – Two classes: shape (n_rows,), the raw sum_j K(x, sv_j) dual_j + b, positive toward classes_[1]. More classes with decision_function_shape='ovo': shape (n_rows, K(K-1)/2), float32, one column per class pair, positive toward the pair’s lower class. With ‘ovr’: shape (n_rows, K), float64, scikit-learn’s vote-plus-confidence transform of the pairwise values.

predict(X)[source]#

Predict class labels for the rows of X.

Two classes: classes_[1] where the decision function is >= 0, otherwise classes_[0]. More classes: one-vs-one vote, the most votes winning and ties going to the lowest class; with break_ties=True (and decision_function_shape='ovr'), the argmax of the ‘ovr’ decision function, the first maximum winning.

Parameters:

X (array-like of shape (n_rows, n_features)) – Query data (the cross-kernel with kernel='precomputed').

Returns:

Array or list of shape (n_rows,) – Labels from classes_: an int64 or float64 Array for integer or float labels, a Python list otherwise.

predict_proba(X)[source]#

Class probabilities from the fitted Platt scaling.

Follows libsvm: each class pair’s decision value goes through its fitted sigmoid (clamped to [1e-7, 1 - 1e-7]); with more than two classes the pairwise probabilities are then coupled.

Parameters:

X (array-like of shape (n_rows, n_features)) – Query data.

Returns:

Array of shape (n_rows, K), float64 – Probabilities, columns in classes_ order.

Raises:

AttributeError – If the model was fitted with probability=False.

predict_log_proba(X)[source]#

Natural log of predict_proba(X).

Parameters:

X (array-like of shape (n_rows, n_features)) – Query data.

Returns:

Array of shape (n_rows, K), float64 – Log probabilities, columns in classes_ order.

Raises:

AttributeError – If the model was fitted with probability=False.

score(X, y)[source]#

Mean accuracy of predict(X) against y.

Parameters:
  • X (array-like of shape (n_rows, n_features)) – Query data.

  • y (array-like of shape (n_rows,)) – True labels.

Returns:

float – Fraction of rows predicted correctly.

save(path)[source]#

Save the fitted model to path as an .npz file.

The file holds the fitted arrays, the hyperparameters, the gamma resolved at fit and the numeric mode. Load it with SVC.load, or predict from it on a CPU without a GPU with mojolearn.host_model(path).

Parameters:

path (str or path-like) – Destination file.

Raises:

RuntimeError – If the model has not been fitted.

classmethod load(path)[source]#

Load a model written by save.

Every array is read at its saved dtype, never cast.

Parameters:

path (str or path-like) – File written by SVC.save.

Returns:

SVC – A fitted model, ready to predict, with the saved numeric mode.

Raises:

ValueError – If the file is not a valid saved SVC.

class mojolearn.svm.SVR(*, kernel='rbf', degree=3, gamma='auto', coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, cache_size=1024.0, verbose=False, max_iter=-1, nochange_steps=1000, output_type=None)[source]#

Bases: NumericModeMixin

Epsilon-support vector regression.

Follows scikit-learn’s SVR, with cuML’s SVR as the reference implementation: an SMO solver with the kernel matrices computed on the GPU. Rows whose prediction falls within epsilon of the target cost nothing and never become support vectors, so raising epsilon can only remove rows from the support set. X is converted to float32 (sparse input is densified); non-finite values in X or y raise an error naming the first bad cell. Supports the 'identical' (default) and 'fast' numeric modes; 'fast' is available on Apple GPUs only.

The parameters keep scikit-learn’s order and meaning, with two defaults that differ: gamma='auto' (scikit-learn uses ‘scale’) and cache_size=1024.0, which here is the prediction buffer in MiB and does not affect training (scikit-learn’s 200 is a training cache). There is no shrinking parameter; passing it raises TypeError. nochange_steps is cuML’s. Every parameter is keyword-only. A parameter that would be ignored is refused: degree with any kernel but ‘poly’, coef0 with any kernel but ‘poly’ or ‘sigmoid’, and a truthy verbose or any output_type raise NotImplementedError.

Parameters:
  • kernel ({‘linear’, ‘rbf’, ‘poly’, ‘sigmoid’, ‘precomputed’}, default ‘rbf’) – The kernel. ‘poly’ is (gamma * <x, y> + coef0) ** degree; ‘sigmoid’ is tanh(gamma * <x, y> + coef0). With ‘precomputed’, X is the n x n kernel matrix at fit and the q x n kernel against the training rows at predict. Other names, including ‘polynomial’ and ‘tanh’, raise.

  • degree (int, default 3) – Degree of the ‘poly’ kernel, an integer in [0, 32]. Must stay 3 with any other kernel.

  • gamma (float, ‘auto’ or ‘scale’, default ‘auto’) – Kernel coefficient, a finite float >= 0. ‘auto’ is 1 / n_features; ‘scale’ is 1 / (n_features * X.var()), computed from the exact variance of the float32 data, so it can differ from scikit-learn’s float32 X.var() in the last bits.

  • coef0 (float, default 0.0) – Independent term of the ‘poly’ and ‘sigmoid’ kernels, finite. Must stay 0.0 with any other kernel.

  • tol (float, default 1e-3) – Stopping tolerance. Must be finite and positive.

  • C (float, default 1.0) – Regularization penalty. Must be finite and positive.

  • epsilon (float, default 0.1) – Half-width of the epsilon-insensitive tube. Must be finite and >= 0; an invalid value is refused when fit runs.

  • cache_size (float, default 1024.0) – Size in MiB of the kernel tile buffer used at prediction, which sets the prediction batch size; results do not depend on it. Must be positive and finite.

  • verbose (bool, default False) – Only False is accepted; this estimator prints no log lines.

  • max_iter (int, default -1) – Cap on the total inner SMO iterations (cuML’s meaning); -1 means no limit. 0 and values below -1 are refused.

  • nochange_steps (int, default 1000) – Follows cuML’s nochange_steps convergence rule. Must be >= 0.

  • output_type (None, default None) – Only None is accepted; results are mojolearn Arrays.

  • numeric_mode ({‘identical’, ‘fast’} or None, default None) – Numeric mode for this estimator; None uses the process default.

Variables:
  • support_ (Array of shape (n_SV,), int32) – Indices of the support vectors in the training data.

  • support_vectors_ (Array of shape (n_SV, n_features), float32) – The support vectors (rows of the kernel matrix with kernel='precomputed').

  • dual_coef_ (Array of shape (1, n_SV), float32) – alpha_i - alpha*_i for each support vector, in scikit-learn’s layout.

  • intercept_ (Array of shape (1,), float32) – Intercept of the decision function.

  • coef_ (Array of shape (1, n_features), float32) – Primal weights dual_coef_ @ support_vectors_, only for kernel='linear'; raises AttributeError otherwise, as scikit-learn does.

  • n_support_ (int) – Number of support vectors (cuML’s scalar form; scikit-learn’s is an array).

  • n_iter_ (int) – Total inner SMO iterations.

  • n_features_in_ (int) – Number of features seen during fit.

Examples

>>> import numpy as np, mojolearn
>>> rng = np.random.default_rng(0)
>>> X = rng.random((1000, 8), dtype=np.float32)
>>> y = X.sum(axis=1)
>>> model = mojolearn.SVR(C=1.0, epsilon=0.1).fit(X, y)
>>> pred = model.predict(X[:5])
fit(X, y, sample_weight=None)[source]#

Fit the support vector regressor.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data, converted to float32. With kernel='precomputed', the square n x n kernel matrix.

  • y (array-like of shape (n_samples,)) – Finite target values.

  • sample_weight (array-like of shape (n_samples,), default None) – Per-sample weights; row i’s penalty becomes C * w_i. None weights every sample equally.

Returns:

self (SVR) – The fitted estimator.

property coef_#

Primal weights, shape (1, n_features), float32.

Only for kernel='linear'; raises AttributeError for other kernels or before fit.

predict(X)[source]#

Predict target values for the rows of X.

Parameters:

X (array-like of shape (n_rows, n_features)) – Query data. With kernel='precomputed', the kernel between the queries and the training rows, shape (n_rows, n_samples).

Returns:

Array of shape (n_rows,), float32 – sum_j K(x, sv_j) dual_j + b for each row.

score(X, y)[source]#

Coefficient of determination R^2 of predict(X) against y.

scikit-learn’s definition, 1 - SS_res / SS_tot, accumulated in float64. A constant y scores 1.0 when predicted exactly and 0.0 otherwise.

Parameters:
  • X (array-like of shape (n_rows, n_features)) – Query data.

  • y (array-like of shape (n_rows,)) – True target values.

Returns:

float – The R^2 score.

save(path)[source]#

Save the fitted model to path as an .npz file.

The file holds the fitted arrays, the hyperparameters, the gamma resolved at fit and the numeric mode. Load it with SVR.load, or predict from it on a CPU without a GPU with mojolearn.host_model(path).

Parameters:

path (str or path-like) – Destination file.

Raises:

RuntimeError – If the model has not been fitted.

classmethod load(path)[source]#

Load a model written by save.

Every array is read at its saved dtype, never cast.

Parameters:

path (str or path-like) – File written by SVR.save.

Returns:

SVR – A fitted model, ready to predict, with the saved numeric mode.

Raises:

ValueError – If the file is not a valid saved SVR.

class mojolearn.svm.LinearSVC(*, penalty='l2', loss='squared_hinge', C=1.0, fit_intercept=True, penalized_intercept=False, class_weight=None, tol=0.0001, max_iter=1000, linesearch_max_iter=100, lbfgs_memory=5, multi_class='ovr')[source]#

Bases: _LinearSVMBase

Linear support vector classification.

Minimizes the hinge or squared hinge loss plus an l2 or l1 penalty (see the mojolearn.svm module description for the objective). Two classes fit one machine; more classes fit one machine per class against the rest, in class order. The intercept is never penalized.

X is read as float32. y is a 1-D array of labels; classes_ is the sorted unique labels. Invalid parameter values raise ValueError.

Parameters:
  • penalty ({‘l2’, ‘l1’}, default ‘l2’) – The regularization term; 'l1' uses OWL-QN and gives exact zeros.

  • loss ({‘squared_hinge’, ‘hinge’}, default ‘squared_hinge’) – The data-fit loss.

  • C (float, default 1.0) – Inverse regularization strength, > 0.

  • fit_intercept (bool, default True) – Whether to fit an (unpenalized) intercept.

  • penalized_intercept (bool, default False) – Only False is supported; True raises NotImplementedError.

  • class_weight (None) – Must be None; anything else raises NotImplementedError.

  • tol (float, default 1e-4) – Gradient tolerance, > 0.

  • max_iter (int, default 1000) – Maximum number of solver iterations per machine.

  • linesearch_max_iter (int, default 100) – Maximum number of line-search steps per iteration.

  • lbfgs_memory (int, default 5) – Number of past updates kept by L-BFGS.

  • multi_class ({‘ovr’}, default ‘ovr’) – One-vs-rest, the only supported value.

  • numeric_mode ({‘identical’, ‘fast’} or None, default None) – The numeric mode for this estimator; None uses the process default (see mojolearn.set_numeric_mode). 'fast' is for Apple GPUs.

Variables:
  • classes_ (list) – The sorted class labels.

  • coef_ (array of shape (1, n_features) or (n_classes, n_features), float32) – Coefficients: one row for two classes, one row per class for more.

  • intercept_ (array of shape (1,) or (n_classes,), float32) – Intercepts; zeros when fit_intercept is False.

  • n_iter_ (array of shape (1,), int64) – The largest iteration count over the machines.

  • objective_ (float or list of float) – The final objective value (one per machine when there are more than two classes).

  • retcode_ (int or list of int) – The solver’s return code, as on LogisticRegression (one per machine when there are more than two classes).

  • n_features_in_ (int) – The number of features seen in fit.

  • input_copied_ (bool) – Whether fit had to copy X to float32 C order.

Examples

>>> import numpy as np, mojolearn
>>> rng = np.random.default_rng(0)
>>> X = rng.random((1000, 8), dtype=np.float32)
>>> y = (X[:, 0] + X[:, 1] > 1.0).astype(np.int64)
>>> clf = mojolearn.LinearSVC(C=10.0).fit(X, y)
>>> labels = clf.predict(X)
fit(X, y, sample_weight=None)[source]#

Fit the classifier.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data, read as float32.

  • y (array-like of shape (n_samples,)) – Class labels, at least two distinct values. A 2-D y, a single class or a length mismatch raises ValueError.

  • sample_weight (None) – Must be None; weights raise NotImplementedError.

Returns:

self (LinearSVC) – The fitted estimator.

decision_function(X)[source]#

Return the linear scores X @ coef_.T + intercept_.

Parameters:

X (array-like of shape (n_samples, n_features)) – Samples, read as float32.

Returns:

scores (array of shape (n_samples,) or (n_samples, n_classes), float32) – For two classes, one score per row (positive means classes_[1]); for more, one score per class.

Raises:

ValueError – If the model is not fitted, or X has a different number of features than the training data.

predict(X)[source]#

Predict class labels.

For two classes a row is classes_[1] when its decision score is positive and classes_[0] otherwise. For more classes it is the class with the highest score; a tie goes to the class that comes first in classes_.

Parameters:

X (array-like of shape (n_samples, n_features)) – Samples, read as float32.

Returns:

labels (array of shape (n_samples,) or list) – An int64 array for integer labels, a float64 array for float labels, and a Python list for any other label type.

score(X, y)[source]#

Return the mean accuracy on the given data.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Test samples.

  • y (array-like of shape (n_samples,)) – True labels.

Returns:

score (float) – The fraction of rows where predict(X) == y.

class mojolearn.svm.LinearSVR(*, epsilon=0.0, penalty='l1', loss='epsilon_insensitive', C=1.0, fit_intercept=True, penalized_intercept=False, tol=0.0001, max_iter=1000, linesearch_max_iter=100, lbfgs_memory=5)[source]#

Bases: _LinearSVMBase

Linear support vector regression.

Minimizes the epsilon-insensitive or squared epsilon-insensitive loss plus an l1 or l2 penalty (see the mojolearn.svm module description for the objective). The intercept is never penalized.

The default penalty is 'l1' (cuML’s default), which uses OWL-QN and gives exact zeros. scikit-learn’s LinearSVR is l2 only: pass penalty='l2' for its objective.

X is read as float32; y must be one-dimensional. Invalid parameter values raise ValueError.

Parameters:
  • epsilon (float, default 0.0) – Width of the insensitive zone, finite and >= 0.

  • penalty ({‘l1’, ‘l2’}, default ‘l1’) – The regularization term.

  • loss ({‘epsilon_insensitive’, ‘squared_epsilon_insensitive’}, default ‘epsilon_insensitive’) – The data-fit loss.

  • C (float, default 1.0) – Inverse regularization strength, > 0.

  • fit_intercept (bool, default True) – Whether to fit an (unpenalized) intercept.

  • penalized_intercept (bool, default False) – Only False is supported; True raises NotImplementedError.

  • tol (float, default 1e-4) – Gradient tolerance, > 0.

  • max_iter (int, default 1000) – Maximum number of solver iterations.

  • linesearch_max_iter (int, default 100) – Maximum number of line-search steps per iteration.

  • lbfgs_memory (int, default 5) – Number of past updates kept by L-BFGS.

  • numeric_mode ({‘identical’, ‘fast’} or None, default None) – The numeric mode for this estimator; None uses the process default (see mojolearn.set_numeric_mode). 'fast' is for Apple GPUs.

Variables:
  • coef_ (array of shape (n_features,), float32) – The fitted coefficients.

  • intercept_ (float) – The fitted intercept; 0.0 when fit_intercept is False.

  • n_iter_ (array of shape (1,), int64) – The number of solver iterations run.

  • objective_ (float) – The final value of the minimized objective.

  • retcode_ (int) – The solver’s return code, as on LogisticRegression.

  • n_features_in_ (int) – The number of features seen in fit.

  • input_copied_ (bool) – Whether fit had to copy X to float32 C order.

Examples

>>> import numpy as np, mojolearn
>>> rng = np.random.default_rng(0)
>>> X = rng.random((1000, 8), dtype=np.float32)
>>> y = X @ np.arange(8, dtype=np.float32) + 1.0
>>> model = mojolearn.LinearSVR(penalty="l2", epsilon=0.1).fit(X, y)
>>> pred = model.predict(X)
fit(X, y, sample_weight=None)[source]#

Fit the regressor.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data, read as float32.

  • y (array-like of shape (n_samples,)) – Target values. A 2-D y or a length mismatch raises ValueError.

  • sample_weight (None) – Must be None; weights raise NotImplementedError.

Returns:

self (LinearSVR) – The fitted estimator.

predict(X)[source]#

Predict with the fitted model.

Parameters:

X (array-like of shape (n_samples, n_features)) – Samples, read as float32.

Returns:

y_pred (array of shape (n_samples,), float32) – X @ coef_ + intercept_.

Raises:

ValueError – If the model is not fitted, or X has a different number of features than the training data.

score(X, y)[source]#

Return the coefficient of determination R^2 of the prediction.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Test samples.

  • y (array-like of shape (n_samples,)) – True target values.

Returns:

score (float) – 1 - SS_res / SS_tot, computed in float64. A constant y scores 0.0.