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 LinearDiscriminantAnalysisLinearDiscriminantAnalysis(
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
| Parameter | Type | Default | Description |
|---|---|---|---|
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 None | None | Covariance shrinkage for "lsqr" and "eigen": None for none, "auto" for Ledoit-Wolf shrinkage, or a float in [0, 1]. |
priors | array-like of shape (n_classes,) or None | None | Class prior probabilities. When None, empirical class proportions are inferred from y. |
n_components | int or None | None | Number of components for dimensionality reduction, bounded by min(n_classes - 1, n_features). |
tol | float | 1e-4 | Absolute threshold for a singular value to be considered significant. |
device | str or None | None | Target compute device ("auto", "cpu", "cuda:0", "cuda:all", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device(). |
Attributes
| Attribute | Type / Shape | Description |
|---|---|---|
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_ | ndarray | Scaling 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_ | int | Number of features seen during fit. |
n_components_ | int | Effective number of discriminant components. |
device_ | str | Active resolved compute device string. |
Methods
| Method | Signature | Description |
|---|---|---|
fit | fit(X, y) -> LinearDiscriminantAnalysis | Fit the LDA model on features X and class labels y. |
predict | predict(X) -> ndarray | Predict class labels for samples in X. |
predict_proba | predict_proba(X) -> ndarray | Estimate class posterior probabilities of shape (n_samples, n_classes). |
predict_log_proba | predict_log_proba(X) -> ndarray | Estimate class log-probabilities of shape (n_samples, n_classes). |
decision_function | decision_function(X) -> ndarray | Predict confidence scores (1D for binary, 2D for multiclass). |
transform | transform(X) -> ndarray | Project X onto the discriminant components to maximize class separation. |
fit_transform | fit_transform(X, y) -> ndarray | Fit LDA on (X, y) and return the projected coordinates. |
score | score(X, y) -> float | Return mean classification accuracy on (X, y). |
to | to(device) -> LinearDiscriminantAnalysis | Move execution target to a new hardware device. |
save | save(path) -> None | Save the fitted model to a binary .dit file. |
load | LinearDiscriminantAnalysis.load(path, device=None) -> LinearDiscriminantAnalysis | Load 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))