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
| Backend | Primitives Used | Support |
|---|---|---|
| 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
| Parameter | Type | Default | Description |
|---|---|---|---|
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"). |
alpha | float | 0.0001 | Constant multiplying the regularization term; also used by the "optimal" learning rate schedule. |
l1_ratio | float | 0.15 | ElasticNet mixing parameter in [0.0, 1.0] when penalty="elasticnet". |
fit_intercept | bool | True | Whether to estimate an intercept term. |
max_iter | int | 1000 | Maximum number of passes over the training data (epochs). |
tol | float | None | 1e-3 | Stopping criterion on epoch loss improvement. None disables early stopping. |
shuffle | bool | True | Whether to shuffle training data after each epoch. |
learning_rate | "optimal" | "constant" | "invscaling" | "optimal" | Learning rate schedule. |
eta0 | float | 0.0 | Initial learning rate for "constant" and "invscaling" schedules. |
power_t | float | 0.5 | Exponent for "invscaling" learning rate decay. |
random_state | int | None | None | Seed controlling epoch shuffling when shuffle=True. |
class_weight | dict | "balanced" | None | None | Class weights ("balanced" or {label: weight}). |
device | str | None | None | Target compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device(). |
Attributes
| Attribute | Type | Description |
|---|---|---|
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_ | int | Number of epochs executed before stopping. |
t_ | float | Total number of weight updates performed during training. |
n_features_in_ | int | Number of features seen during fit. |
device_ | str | Resolved hardware device string used by the estimator. |
Methods
| Method | Signature | Description |
|---|---|---|
fit | fit(X, y, sample_weight=None) -> self | Fit linear classifier with SGD. |
decision_function | decision_function(X) -> ndarray | Predict signed confidence scores for samples. |
predict_proba | predict_proba(X) -> ndarray | Probability estimates (available for loss="log_loss" or "modified_huber"). |
predict_log_proba | predict_log_proba(X) -> ndarray | Log probability estimates (available for loss="log_loss" or "modified_huber"). |
predict | predict(X) -> ndarray | Predict class labels for samples in X. |
score | score(X, y, sample_weight=None) -> float | Return mean classification accuracy on (X, y). |
to | to(device: str) -> self | Move the estimator execution target to another hardware device. |
save / load | clf.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]))