Skip to Content
OchreML
Decomposition & Manifold

LinearDiscriminantAnalysis

Supervised linear classifier and dimensionality reducer maximizing between-class to within-class variance separation.

LinearDiscriminantAnalysis (LDA) fits a Gaussian class-conditional density to each class with a shared covariance matrix. It serves both as a fast linear classifier (predict, predict_proba, decision_function) and as a supervised dimensionality reducer (transform, fit_transform) projecting features onto at most min(n_classes - 1, n_features) discriminant axes. Supports SVD, least-squares, and eigendecomposition solvers with optional Ledoit-Wolf shrinkage. (^▽^)

Backend Support

  • Backend primitives: E1–E5 (dense linear algebra and scatter/covariance matrix ops), N5 (SVD / eigendecomposition).
  • Supported devices: "auto", "cpu", "cuda:0", "cuda:all", "wgpu", "tpu:0". Falls back cleanly to multi-threaded Rayon CPU (f64) when an accelerator is unavailable.

Import & Signature

from ochreml.discriminant_analysis import LinearDiscriminantAnalysis
# Or via top-level lazy import:
from ochreml import LinearDiscriminantAnalysis
LinearDiscriminantAnalysis(
    solver: str = "svd",
    shrinkage: Optional[Union[str, float]] = None,
    priors: Optional[Any] = None,
    n_components: Optional[int] = None,
    tol: float = 1e-4,
    device: Optional[str] = None,
)

Parameters

ParameterTypeDefaultDescription
solver{"svd", "lsqr", "eigen"}"svd"Solver to use: "svd" (recommended for large feature counts, no shrinkage), "lsqr" (least squares, supports shrinkage), or "eigen" (eigendecomposition, supports shrinkage).
shrinkage"auto", float, or NoneNoneCovariance shrinkage for "lsqr" and "eigen": None for none, "auto" for Ledoit-Wolf shrinkage, or a float in [0, 1].
priorsarray-like of shape (n_classes,) or NoneNoneClass prior probabilities. When None, empirical class proportions are inferred from y.
n_componentsint or NoneNoneNumber of components for dimensionality reduction, bounded by min(n_classes - 1, n_features).
tolfloat1e-4Absolute threshold for a singular value to be considered significant.
devicestr or NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "cuda:all", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeType / ShapeDescription
classes_ndarray of shape (n_classes,)Unique class labels discovered during fit.
priors_ndarray of shape (n_classes,)Class prior probabilities (sum to 1).
means_ndarray of shape (n_classes, n_features_in_)Class-wise feature means.
xbar_ndarray of shape (n_features_in_,)Overall feature mean across all training samples.
coef_ndarray of shape (n_classes, n_features_in_) or (1, n_features_in_)Linear decision weight vectors.
intercept_ndarray of shape (n_classes,) or (1,)Linear decision intercept terms.
scalings_ndarrayScaling matrix projecting features into the discriminant subspace.
explained_variance_ratio_ndarray of shape (n_components_,)Percentage of between-class variance explained by each discriminant component.
n_features_in_intNumber of features seen during fit.
n_components_intEffective number of discriminant components.
device_strActive resolved compute device string.

Methods

MethodSignatureDescription
fitfit(X, y) -> LinearDiscriminantAnalysisFit the LDA model on features X and class labels y.
predictpredict(X) -> ndarrayPredict class labels for samples in X.
predict_probapredict_proba(X) -> ndarrayEstimate class posterior probabilities of shape (n_samples, n_classes).
predict_log_probapredict_log_proba(X) -> ndarrayEstimate class log-probabilities of shape (n_samples, n_classes).
decision_functiondecision_function(X) -> ndarrayPredict confidence scores (1D for binary, 2D for multiclass).
transformtransform(X) -> ndarrayProject X onto the discriminant components to maximize class separation.
fit_transformfit_transform(X, y) -> ndarrayFit LDA on (X, y) and return the projected coordinates.
scorescore(X, y) -> floatReturn mean classification accuracy on (X, y).
toto(device) -> LinearDiscriminantAnalysisMove execution target to a new hardware device.
savesave(path) -> NoneSave the fitted model to a binary .dit file.
loadLinearDiscriminantAnalysis.load(path, device=None) -> LinearDiscriminantAnalysisLoad a saved model from a .dit file (also supported via ochreml.load).

Example

import numpy as np
import ochreml
from ochreml.discriminant_analysis import LinearDiscriminantAnalysis

rng = np.random.default_rng(42)
X0 = rng.normal(loc=[-2.0, 0.0, 0.0, 0.0], scale=0.8, size=(60, 4))
X1 = rng.normal(loc=[0.0, 2.0, 0.0, 0.0], scale=0.8, size=(60, 4))
X2 = rng.normal(loc=[2.0, -1.5, 0.5, 0.0], scale=0.8, size=(60, 4))
X = np.vstack([X0, X1, X2])
y = np.repeat([0, 1, 2], 60)

lda = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto", n_components=2)
X_proj = lda.fit_transform(X, y)

print("Projected shape:", X_proj.shape)
print("Accuracy:", round(lda.score(X, y), 4))
print("First 3 class probabilities:\n", np.round(lda.predict_proba(X[:3]), 4))

lda.save("lda_model.dit")
loaded = ochreml.load("lda_model.dit", device="cpu")
assert np.array_equal(lda.predict(X), loaded.predict(X))

On this page