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
| 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 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
| Parameter | Type | Default | Description |
|---|---|---|---|
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"). |
alpha | float | 0.0001 | Constant multiplying the regularization term. |
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 | "invscaling" | "constant" | "optimal" | "invscaling" | Learning rate schedule. |
eta0 | float | 0.01 | Initial learning rate for "invscaling" and "constant" schedules. |
power_t | float | 0.25 | Exponent for "invscaling" learning rate decay. |
epsilon | float | 0.1 | Threshold parameter used by "huber" and "epsilon_insensitive" losses. |
random_state | int | None | None | Seed controlling epoch shuffling when shuffle=True. |
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 (n_features,) | Weights assigned to the features. |
intercept_ | ndarray of shape (1,) | Intercept (bias) term. |
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 regression model with SGD. |
predict | predict(X) -> ndarray | Predict continuous target values for input matrix X. |
score | score(X, y) -> float | Return coefficient of determination R^2. |
to | to(device: str) -> self | Move the estimator execution target to another hardware device. |
save / load | reg.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]))