Documentation
Classes
SGDClassifier

SGDClassifier

Linear classifiers (SVM, logistic regression, etc.) with SGD training.

This estimator implements regularized linear models with stochastic gradient descent (SGD) learning: the gradient of the loss is estimated each sample at a time and the model is updated along the way with a decreasing strength schedule (aka learning rate). SGD allows minibatch (online/out-of-core) learning via the partial\_fit method. For best results using the default learning rate schedule, the data should have zero mean and unit variance.

This implementation works with data represented as dense or sparse arrays of floating point values for the features. The model it fits can be controlled with the loss parameter; by default, it fits a linear support vector machine (SVM).

The regularizer is a penalty added to the loss function that shrinks model parameters towards the zero vector using either the squared euclidean norm L2 or the absolute norm L1 or a combination of both (Elastic Net). If the parameter update crosses the 0.0 value because of the regularizer, the update is truncated to 0.0 to allow for learning sparse models and achieve online feature selection.

Read more in the User Guide.

Python Reference (opens in a new tab)

Constructors

constructor()

Signature

new SGDClassifier(opts?: object): SGDClassifier;

Parameters

NameTypeDescription
opts?object-
opts.alpha?numberConstant that multiplies the regularization term. The higher the value, the stronger the regularization. Also used to compute the learning rate when learning\_rate is set to ‘optimal’. Values must be in the range \[0.0, inf). Default Value 0.0001
opts.average?number | booleanWhen set to true, computes the averaged SGD weights across all updates and stores the result in the coef\_ attribute. If set to an int greater than 1, averaging will begin once the total number of samples seen reaches average. So average=10 will begin averaging after seeing 10 samples. Integer values must be in the range \[1, n\_samples\]. Default Value false
opts.class_weight?anyPreset for the class_weight fit parameter. Weights associated with classes. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n\_samples / (n\_classes \* np.bincount(y)).
opts.early_stopping?booleanWhether to use early stopping to terminate training when validation score is not improving. If set to true, it will automatically set aside a stratified fraction of training data as validation and terminate training when validation score returned by the score method is not improving by at least tol for n_iter_no_change consecutive epochs. Default Value false
opts.epsilon?numberEpsilon in the epsilon-insensitive loss functions; only if loss is ‘huber’, ‘epsilon_insensitive’, or ‘squared_epsilon_insensitive’. For ‘huber’, determines the threshold at which it becomes less important to get the prediction exactly right. For epsilon-insensitive, any differences between the current prediction and the correct label are ignored if they are less than this threshold. Values must be in the range \[0.0, inf). Default Value 0.1
opts.eta0?numberThe initial learning rate for the ‘constant’, ‘invscaling’ or ‘adaptive’ schedules. The default value is 0.0 as eta0 is not used by the default schedule ‘optimal’. Values must be in the range (0.0, inf). Default Value 0
opts.fit_intercept?booleanWhether the intercept should be estimated or not. If false, the data is assumed to be already centered. Default Value true
opts.l1_ratio?numberThe Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. Only used if penalty is ‘elasticnet’. Values must be in the range \[0.0, 1.0\]. Default Value 0.15
opts.learning_rate?stringThe learning rate schedule: Default Value 'optimal'
opts.loss?"log_loss" | "squared_error" | "huber" | "hinge" | "modified_huber" | "squared_hinge" | "perceptron" | "epsilon_insensitive" | "squared_epsilon_insensitive"The loss function to be used. Default Value 'hinge'
opts.max_iter?numberThe maximum number of passes over the training data (aka epochs). It only impacts the behavior in the fit method, and not the partial\_fit method. Values must be in the range \[1, inf). Default Value 1000
opts.n_iter_no_change?numberNumber of iterations with no improvement to wait before stopping fitting. Convergence is checked against the training loss or the validation loss depending on the early\_stopping parameter. Integer values must be in the range \[1, max\_iter). Default Value 5
opts.n_jobs?numberThe number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. undefined means 1 unless in a joblib.parallel\_backend (opens in a new tab) context. \-1 means using all processors. See Glossary for more details.
opts.penalty?"l1" | "l2" | "elasticnet"The penalty (aka regularization term) to be used. Defaults to ‘l2’ which is the standard regularizer for linear SVM models. ‘l1’ and ‘elasticnet’ might bring sparsity to the model (feature selection) not achievable with ‘l2’. No penalty is added when set to undefined. Default Value 'l2'
opts.power_t?numberThe exponent for inverse scaling learning rate [default 0.5]. Values must be in the range (-inf, inf). Default Value 0.5
opts.random_state?numberUsed for shuffling the data, when shuffle is set to true. Pass an int for reproducible output across multiple function calls. See Glossary. Integer values must be in the range \[0, 2\*\*32 \- 1\].
opts.shuffle?booleanWhether or not the training data should be shuffled after each epoch. Default Value true
opts.tol?numberThe stopping criterion. If it is not undefined, training will stop when (loss > best_loss - tol) for n\_iter\_no\_change consecutive epochs. Convergence is checked against the training loss or the validation loss depending on the early\_stopping parameter. Values must be in the range \0.0, inf). Default Value 0.001
opts.validation_fraction?numberThe proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early\_stopping is true. Values must be in the range (0.0, 1.0). Default Value 0.1
opts.verbose?numberThe verbosity level. Values must be in the range \[0, inf). Default Value 0
opts.warm_start?booleanWhen set to true, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See [the Glossary. Repeatedly calling fit or partial_fit when warm_start is true can result in a different solution than when calling fit a single time because of the way the data is shuffled. If a dynamic learning rate is used, the learning rate is adapted depending on the number of samples already seen. Calling fit resets this counter, while partial\_fit will result in increasing the existing counter. Default Value false

Returns

SGDClassifier

Defined in: generated/linear_model/SGDClassifier.ts:29 (opens in a new tab)

Methods

decision_function()

Predict confidence scores for samples.

The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane.

Signature

decision_function(opts: object): Promise<ArrayLike>;

Parameters

NameTypeDescription
optsobject-
opts.X?ArrayLikeThe data matrix for which we want to get the confidence scores.

Returns

Promise<ArrayLike>

Defined in: generated/linear_model/SGDClassifier.ts:286 (opens in a new tab)

densify()

Convert coefficient matrix to dense array format.

Converts the coef\_ member (back) to a numpy.ndarray. This is the default format of coef\_ and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op.

Signature

densify(opts: object): Promise<any>;

Parameters

NameType
optsobject

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:323 (opens in a new tab)

dispose()

Disposes of the underlying Python resources.

Once dispose() is called, the instance is no longer usable.

Signature

dispose(): Promise<void>;

Returns

Promise<void>

Defined in: generated/linear_model/SGDClassifier.ts:267 (opens in a new tab)

fit()

Fit linear model with Stochastic Gradient Descent.

Signature

fit(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.X?anyTraining data.
opts.coef_init?ArrayLike[]The initial coefficients to warm-start the optimization.
opts.intercept_init?ArrayLikeThe initial intercept to warm-start the optimization.
opts.sample_weight?ArrayLikeWeights applied to individual samples. If not provided, uniform weights are assumed. These weights will be multiplied with class_weight (passed through the constructor) if class_weight is specified.
opts.y?ArrayLikeTarget values.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:349 (opens in a new tab)

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Signature

get_metadata_routing(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.routing?anyA MetadataRequest encapsulating routing information.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:412 (opens in a new tab)

init()

Initializes the underlying Python resources.

This instance is not usable until the Promise returned by init() resolves.

Signature

init(py: PythonBridge): Promise<void>;

Parameters

NameType
pyPythonBridge

Returns

Promise<void>

Defined in: generated/linear_model/SGDClassifier.ts:203 (opens in a new tab)

partial_fit()

Perform one epoch of stochastic gradient descent on given samples.

Internally, this method uses max\_iter \= 1. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence, early stopping, and learning rate adjustments should be handled by the user.

Signature

partial_fit(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.X?anySubset of the training data.
opts.classes?ArrayLikeClasses across all calls to partial_fit. Can be obtained by via np.unique(y\_all), where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn’t need to contain all labels in classes.
opts.sample_weight?ArrayLikeWeights applied to individual samples. If not provided, uniform weights are assumed.
opts.y?ArrayLikeSubset of the target values.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:449 (opens in a new tab)

predict()

Predict class labels for samples in X.

Signature

predict(opts: object): Promise<ArrayLike>;

Parameters

NameTypeDescription
optsobject-
opts.X?ArrayLikeThe data matrix for which we want to get the predictions.

Returns

Promise<ArrayLike>

Defined in: generated/linear_model/SGDClassifier.ts:501 (opens in a new tab)

predict_log_proba()

Log of probability estimates.

This method is only available for log loss and modified Huber loss.

When loss=”modified_huber”, probability estimates may be hard zeros and ones, so taking the logarithm is not possible.

See predict\_proba for details.

Signature

predict_log_proba(opts: object): Promise<ArrayLike>;

Parameters

NameTypeDescription
optsobject-
opts.X?ArrayLikeInput data for prediction.

Returns

Promise<ArrayLike>

Defined in: generated/linear_model/SGDClassifier.ts:540 (opens in a new tab)

predict_proba()

Probability estimates.

This method is only available for log loss and modified Huber loss.

Multiclass probability estimates are derived from binary (one-vs.-rest) estimates by simple normalization, as recommended by Zadrozny and Elkan.

Binary probability estimates for loss=”modified_huber” are given by (clip(decision_function(X), -1, 1) + 1) / 2. For other loss functions it is necessary to perform proper probability calibration by wrapping the classifier with CalibratedClassifierCV instead.

Signature

predict_proba(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.X?anyInput data for prediction.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:581 (opens in a new tab)

score()

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Signature

score(opts: object): Promise<number>;

Parameters

NameTypeDescription
optsobject-
opts.X?ArrayLike[]Test samples.
opts.sample_weight?ArrayLikeSample weights.
opts.y?ArrayLikeTrue labels for X.

Returns

Promise<number>

Defined in: generated/linear_model/SGDClassifier.ts:616 (opens in a new tab)

set_fit_request()

Request metadata passed to the fit method.

Note that this method is only relevant if enable\_metadata\_routing=True (see sklearn.set\_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

Signature

set_fit_request(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.coef_init?string | booleanMetadata routing for coef\_init parameter in fit.
opts.intercept_init?string | booleanMetadata routing for intercept\_init parameter in fit.
opts.sample_weight?string | booleanMetadata routing for sample\_weight parameter in fit.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:667 (opens in a new tab)

set_partial_fit_request()

Request metadata passed to the partial\_fit method.

Note that this method is only relevant if enable\_metadata\_routing=True (see sklearn.set\_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

Signature

set_partial_fit_request(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.classes?string | booleanMetadata routing for classes parameter in partial\_fit.
opts.sample_weight?string | booleanMetadata routing for sample\_weight parameter in partial\_fit.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:716 (opens in a new tab)

set_score_request()

Request metadata passed to the score method.

Note that this method is only relevant if enable\_metadata\_routing=True (see sklearn.set\_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

Signature

set_score_request(opts: object): Promise<any>;

Parameters

NameTypeDescription
optsobject-
opts.sample_weight?string | booleanMetadata routing for sample\_weight parameter in score.

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:760 (opens in a new tab)

sparsify()

Convert coefficient matrix to sparse format.

Converts the coef\_ member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation.

The intercept\_ member is not converted.

Signature

sparsify(opts: object): Promise<any>;

Parameters

NameType
optsobject

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:799 (opens in a new tab)

Properties

_isDisposed

boolean = false

Defined in: generated/linear_model/SGDClassifier.ts:27 (opens in a new tab)

_isInitialized

boolean = false

Defined in: generated/linear_model/SGDClassifier.ts:26 (opens in a new tab)

_py

PythonBridge

Defined in: generated/linear_model/SGDClassifier.ts:25 (opens in a new tab)

id

string

Defined in: generated/linear_model/SGDClassifier.ts:22 (opens in a new tab)

opts

any

Defined in: generated/linear_model/SGDClassifier.ts:23 (opens in a new tab)

Accessors

classes_

Signature

classes_(): Promise<any[]>;

Returns

Promise<any[]>

Defined in: generated/linear_model/SGDClassifier.ts:915 (opens in a new tab)

coef_

Weights assigned to the features.

Signature

coef_(): Promise<ArrayLike[][]>;

Returns

Promise<ArrayLike[][]>

Defined in: generated/linear_model/SGDClassifier.ts:825 (opens in a new tab)

feature_names_in_

Names of features seen during fit. Defined only when X has feature names that are all strings.

Signature

feature_names_in_(): Promise<ArrayLike>;

Returns

Promise<ArrayLike>

Defined in: generated/linear_model/SGDClassifier.ts:988 (opens in a new tab)

intercept_

Constants in decision function.

Signature

intercept_(): Promise<ArrayLike[]>;

Returns

Promise<ArrayLike[]>

Defined in: generated/linear_model/SGDClassifier.ts:848 (opens in a new tab)

loss_function_

Signature

loss_function_(): Promise<any>;

Returns

Promise<any>

Defined in: generated/linear_model/SGDClassifier.ts:893 (opens in a new tab)

n_features_in_

Number of features seen during fit.

Signature

n_features_in_(): Promise<number>;

Returns

Promise<number>

Defined in: generated/linear_model/SGDClassifier.ts:963 (opens in a new tab)

n_iter_

The actual number of iterations before reaching the stopping criterion. For multiclass fits, it is the maximum over every binary fit.

Signature

n_iter_(): Promise<number>;

Returns

Promise<number>

Defined in: generated/linear_model/SGDClassifier.ts:873 (opens in a new tab)

py

Signature

py(): PythonBridge;

Returns

PythonBridge

Defined in: generated/linear_model/SGDClassifier.ts:190 (opens in a new tab)

Signature

py(pythonBridge: PythonBridge): void;

Parameters

NameType
pythonBridgePythonBridge

Returns

void

Defined in: generated/linear_model/SGDClassifier.ts:194 (opens in a new tab)

t_

Number of weight updates performed during training. Same as (n\_iter\_ \* n\_samples + 1).

Signature

t_(): Promise<number>;

Returns

Promise<number>

Defined in: generated/linear_model/SGDClassifier.ts:940 (opens in a new tab)