Skip to Content
OchreML
Linear, GLM & Linear SVM

SGDRegressor

Linear regression fitted by minimizing regularized empirical loss with Stochastic Gradient Descent.

Overview

SGDRegressor fits a regularized linear regression model using Stochastic Gradient Descent over selectable regression losses ("squared_error", "huber", "epsilon_insensitive") and penalties ("l2", "l1", "elasticnet", "none"). It is designed for scalable regression on large datasets and supports configurable learning rate schedules.

When to Use

  • Large-scale regression tasks where closed-form Gram matrix solvers are too costly in memory or time.
  • Combining robust losses ("huber", "epsilon_insensitive") with L1, L2, or ElasticNet regularization.
  • Standardize input features (e.g., via StandardScaler) before fitting for stable SGD convergence.

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 SGDRegressor
# or top-level lazy import:
from ochreml import SGDRegressor

reg = SGDRegressor(
    loss: str = "squared_error",
    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 = "invscaling",
    eta0: float = 0.01,
    power_t: float = 0.25,
    epsilon: float = 0.1,
    random_state: int | None = None,
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
loss"squared_error" | "huber" | "epsilon_insensitive""squared_error"Empirical regression loss function.
penalty"l2" | "l1" | "elasticnet" | "none" | None"l2"Regularization term (None is treated as "none").
alphafloat0.0001Constant multiplying the regularization term.
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"invscaling" | "constant" | "optimal""invscaling"Learning rate schedule.
eta0float0.01Initial learning rate for "invscaling" and "constant" schedules.
power_tfloat0.25Exponent for "invscaling" learning rate decay.
epsilonfloat0.1Threshold parameter used by "huber" and "epsilon_insensitive" losses.
random_stateint | NoneNoneSeed controlling epoch shuffling when shuffle=True.
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
coef_ndarray of shape (n_features,)Weights assigned to the features.
intercept_ndarray of shape (1,)Intercept (bias) term.
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 regression model with SGD.
predictpredict(X) -> ndarrayPredict continuous target values for input matrix X.
scorescore(X, y) -> floatReturn coefficient of determination R^2.
toto(device: str) -> selfMove the estimator execution target to another hardware device.
save / loadreg.save(path) / SGDRegressor.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 SGDRegressor

rng = np.random.default_rng(99)
X = rng.standard_normal((600, 5))
y = X @ np.array([2.0, -1.5, 0.5, 3.0, -0.8]) + 1.0 + rng.normal(0.0, 0.2, size=600)

reg = SGDRegressor(
    loss="squared_error",
    penalty="l2",
    alpha=1e-4,
    learning_rate="invscaling",
    eta0=0.01,
    random_state=42,
    device="auto",
)
reg.fit(X, y)

preds = reg.predict(X[:5])
print(f"R^2: {reg.score(X, y):.4f}, epochs: {reg.n_iter_}, updates: {reg.t_:.0f}")

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

On this page