Linear, GLM & Linear SVM
LogisticRegression
L2-regularized binary and multinomial logistic regression trained with hardware-accelerated L-BFGS.
Overview
LogisticRegression fits an L2-regularized logistic (cross-entropy) classification model for binary and multiclass (softmax / multinomial) targets using L-BFGS optimization. Regularization strength is controlled by the inverse penalty parameter C (larger C means weaker regularization), with support for class imbalance via class_weight and per-sample weights via sample_weight.
When to Use
- Binary and multiclass linear classification where well-calibrated probability estimates (
predict_proba/predict_log_proba) are needed. - Imbalanced classification datasets using
class_weight="balanced"or a custom{class_label: weight}mapping. - Interpretability-focused classification where feature weights directly indicate log-odds contributions.
Hardware Backend Support
| Backend | Primitives Used | Support |
|---|---|---|
| CPU (Rayon) | Dense E1-E5, N2 (f64) | Full (default fallback) |
CUDA (cuda:0, cuda:all) | cuBLAS FP64 matmul/matvec & L-BFGS gradients (E1-E5, N2) | Full |
wgpu (wgpu) | WGSL compute shaders (E1-E5, N2) | Full |
TPU (tpu:0) | OpenXLA PJRT StableHLO dot_general (E1-E5, N2) | Full |
Import & Constructor
from ochreml.linear_model import LogisticRegression
# or top-level lazy import:
from ochreml import LogisticRegression
clf = LogisticRegression(
C: float = 1.0,
fit_intercept: bool = True,
max_iter: int = 100,
tol: float = 1e-4,
class_weight: dict | str | None = None,
device: str | None = None,
)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
C | float | 1.0 | Inverse of L2 regularization strength; must be strictly positive. Smaller values specify stronger regularization. |
fit_intercept | bool | True | Specifies if a bias/intercept term should be added to the decision function. |
max_iter | int | 100 | Maximum number of L-BFGS iterations. |
tol | float | 1e-4 | Stopping tolerance on the L-BFGS gradient norm. |
class_weight | dict | "balanced" | None | None | Weights associated with classes ("balanced" adjusts inversely proportional to class frequencies, or pass {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) | Estimated linear coefficients per class. |
intercept_ | ndarray of shape (1,) or (n_classes,) | Intercept (bias) added to the decision function. |
classes_ | ndarray of shape (n_classes,) | Sorted unique class labels seen during fit. |
n_iter_ | int | Number of L-BFGS iterations executed. |
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 logistic regression model on training data. |
decision_function | decision_function(X) -> ndarray | Compute raw log-odds / margin scores for samples. |
predict_proba | predict_proba(X) -> ndarray | Return probability estimates of shape (n_samples, n_classes). |
predict_log_proba | predict_log_proba(X) -> ndarray | Return natural logarithm of probability estimates. |
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) / LogisticRegression.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 LogisticRegression
rng = np.random.default_rng(42)
X0 = rng.normal(loc=[-1.5, -1.0], scale=0.9, size=(200, 2))
X1 = rng.normal(loc=[1.5, 1.0], scale=0.9, size=(200, 2))
X = np.vstack([X0, X1])
y = np.array([0] * 200 + [1] * 200, dtype=np.float64)
clf = LogisticRegression(C=1.0, max_iter=200, class_weight="balanced", 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}, n_iter_: {clf.n_iter_}")
# Persist to .dit and reload
clf.save("logreg.dit")
loaded = ochreml.load("logreg.dit", device="cpu")
assert np.allclose(probs, loaded.predict_proba(X[:5]))