Skip to Content
OchreML
Linear, GLM & Linear SVM

SGDClassifier

Linear classifiers (SVM, logistic regression, modified Huber) trained with Stochastic Gradient Descent.

Overview

SGDClassifier trains regularized linear classifiers using Stochastic Gradient Descent (SGD) over configurable loss functions ("hinge" for linear SVM, "log_loss" for logistic regression, "modified_huber" for smooth outlier-tolerant classification) and penalties ("l2", "l1", "elasticnet", "none"). It supports binary and multiclass (one-vs-rest) classification, flexible learning rate schedules, and class/sample weighting.

When to Use

  • Large-scale classification datasets where full-batch solvers (LogisticRegression, LinearSVC) are memory- or compute-heavy.
  • Switching rapidly between linear SVM (loss="hinge"), logistic regression (loss="log_loss"), and L1/ElasticNet sparse linear classification.
  • Feature matrices should be standardized (for example with StandardScaler) prior to fitting because SGD is sensitive to feature scaling.

Hardware Backend Support

BackendPrimitives UsedSupport
CPU (Rayon)E3, N2 (f64)Full (default fallback)
CUDA (cuda:0, cuda:all)cuBLAS FP64 matvec (E3, N2)Full
wgpu (wgpu)WGSL compute shaders (E3, N2)Full
TPU (tpu:0)OpenXLA PJRT (E3, N2)Full

Import & Constructor

from ochreml.linear_model import SGDClassifier
# or top-level lazy import:
from ochreml import SGDClassifier

clf = SGDClassifier(
    loss: str = "hinge",
    penalty: str | None = "l2",
    alpha: float = 0.0001,
    l1_ratio: float = 0.15,
    fit_intercept: bool = True,
    max_iter: int = 1000,
    tol: float | None = 1e-3,
    shuffle: bool = True,
    learning_rate: str = "optimal",
    eta0: float = 0.0,
    power_t: float = 0.5,
    random_state: int | None = None,
    class_weight: dict | str | None = None,
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
loss"hinge" | "log_loss" | "modified_huber""hinge"Loss function to optimize. "log_loss" and "modified_huber" enable predict_proba.
penalty"l2" | "l1" | "elasticnet" | "none" | None"l2"Regularization term (None is treated as "none").
alphafloat0.0001Constant multiplying the regularization term; also used by the "optimal" learning rate schedule.
l1_ratiofloat0.15ElasticNet mixing parameter in [0.0, 1.0] when penalty="elasticnet".
fit_interceptboolTrueWhether to estimate an intercept term.
max_iterint1000Maximum number of passes over the training data (epochs).
tolfloat | None1e-3Stopping criterion on epoch loss improvement. None disables early stopping.
shuffleboolTrueWhether to shuffle training data after each epoch.
learning_rate"optimal" | "constant" | "invscaling""optimal"Learning rate schedule.
eta0float0.0Initial learning rate for "constant" and "invscaling" schedules.
power_tfloat0.5Exponent for "invscaling" learning rate decay.
random_stateint | NoneNoneSeed controlling epoch shuffling when shuffle=True.
class_weightdict | "balanced" | NoneNoneClass weights ("balanced" or {label: weight}).
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
coef_ndarray of shape (1, n_features) or (n_classes, n_features)Weights assigned to the features.
intercept_ndarray of shape (1,) or (n_classes,)Constants in the decision function.
classes_ndarray of shape (n_classes,)Sorted unique class labels.
n_iter_intNumber of epochs executed before stopping.
t_floatTotal number of weight updates performed during training.
n_features_in_intNumber of features seen during fit.
device_strResolved hardware device string used by the estimator.

Methods

MethodSignatureDescription
fitfit(X, y, sample_weight=None) -> selfFit linear classifier with SGD.
decision_functiondecision_function(X) -> ndarrayPredict signed confidence scores for samples.
predict_probapredict_proba(X) -> ndarrayProbability estimates (available for loss="log_loss" or "modified_huber").
predict_log_probapredict_log_proba(X) -> ndarrayLog probability estimates (available for loss="log_loss" or "modified_huber").
predictpredict(X) -> ndarrayPredict class labels for samples in X.
scorescore(X, y, sample_weight=None) -> floatReturn mean classification accuracy on (X, y).
toto(device: str) -> selfMove the estimator execution target to another hardware device.
save / loadclf.save(path) / SGDClassifier.load(path, device=None)Persist or restore the model in OchreML's binary .dit format.

Usage Example

import numpy as np
import ochreml
from ochreml.linear_model import SGDClassifier

rng = np.random.default_rng(7)
X0 = rng.normal(loc=-1.2, scale=0.8, size=(250, 4))
X1 = rng.normal(loc=1.2, scale=0.8, size=(250, 4))
X = np.vstack([X0, X1])
y = np.array([0] * 250 + [1] * 250, dtype=np.float64)

clf = SGDClassifier(
    loss="log_loss",
    penalty="l2",
    alpha=1e-4,
    max_iter=500,
    random_state=42,
    device="auto",
)
clf.fit(X, y)

probs = clf.predict_proba(X[:5])
preds = clf.predict(X[:5])
print(f"Accuracy: {clf.score(X, y):.4f}, epochs: {clf.n_iter_}, updates: {clf.t_:.0f}")

# Persist to .dit and reload
clf.save("sgd_clf.dit")
loaded = ochreml.load("sgd_clf.dit", device="cpu")
assert np.array_equal(preds, loaded.predict(X[:5]))

On this page