Skip to Content
OchreML
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

BackendPrimitives UsedSupport
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

ParameterTypeDefaultDescription
Cfloat1.0Inverse of L2 regularization strength; must be strictly positive. Smaller values specify stronger regularization.
fit_interceptboolTrueSpecifies if a bias/intercept term should be added to the decision function.
max_iterint100Maximum number of L-BFGS iterations.
tolfloat1e-4Stopping tolerance on the L-BFGS gradient norm.
class_weightdict | "balanced" | NoneNoneWeights associated with classes ("balanced" adjusts inversely proportional to class frequencies, or pass {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)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_intNumber of L-BFGS iterations executed.
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 logistic regression model on training data.
decision_functiondecision_function(X) -> ndarrayCompute raw log-odds / margin scores for samples.
predict_probapredict_proba(X) -> ndarrayReturn probability estimates of shape (n_samples, n_classes).
predict_log_probapredict_log_proba(X) -> ndarrayReturn natural logarithm of probability estimates.
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) / 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]))

On this page