Skip to Content
OchreML
Clustering, Neighbors & NB

ComplementNB

Complement Naive Bayes classifier tailored for imbalanced non-negative count datasets with optional weight normalization and partial_fit.

Overview & Backend Support

ComplementNB adapts the Multinomial Naive Bayes algorithm for imbalanced datasets by estimating feature weights from the complement of each class (all samples not belonging to class c) rather than only samples within class c. Optional L1 weight normalization (norm=True) further stabilizes text classification performance.

  • Backend primitives: N1 reduction primitives across CPU (Rayon), CUDA, wgpu, and Google TPU.
  • Incremental learning (partial_fit): Supported. Pass classes on the first partial_fit(X_batch, y_batch, classes=all_classes, sample_weight=...) call to stream non-negative batches incrementally.
  • Persistence: Supports binary .dit serialization via save(path), ComplementNB.load(path, device=...), ochreml.save(), and ochreml.load().

Import & Signature

from ochreml.naive_bayes import ComplementNB
# or lazily from top-level:
from ochreml import ComplementNB

ComplementNB(
    alpha: float = 1.0,
    fit_prior: bool = True,
    class_prior: Any | None = None,
    norm: bool = False,
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
alphafloat1.0Additive (Laplace/Lidstone) smoothing parameter (0.0 for no smoothing).
fit_priorboolTrueWhether to learn class prior probabilities from data; if False, a uniform prior is used.
class_priorarray-like of shape (n_classes,) | NoneNoneExplicit prior probabilities of the classes. If specified, priors are not adjusted according to data.
normboolFalseWhether to apply a second L1 normalization step to the complement feature weights.
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
classes_ndarray of shape (n_classes,) | NoneUnique class labels (float64) known to the classifier.
class_count_ndarray of shape (n_classes,) | NoneNumber (or total weight) of training samples observed in each class.
class_log_prior_ndarray of shape (n_classes,) | NoneSmoothed empirical log probability for each class.
feature_count_ndarray of shape (n_classes, n_features) | NoneAccumulated feature counts (or weighted counts) per class.
feature_all_ndarray of shape (n_features,) | NoneTotal count of each feature across all classes.
feature_log_prob_ndarray of shape (n_classes, n_features) | NoneComplement log-weight matrix for each class and feature.
n_features_in_int | NoneNumber of features seen during fit or partial_fit.
device_str | NoneResolved hardware device string used by the underlying Rust model.

Methods

MethodSignatureDescription
fitfit(X, y, sample_weight=None) -> ComplementNBFit Complement Naive Bayes on non-negative features X and targets y.
partial_fitpartial_fit(X, y, classes=None, sample_weight=None) -> ComplementNBIncrementally update complement counts and weights on a batch of non-negative samples.
predictpredict(X) -> ndarrayPredict class labels (float64, shape (n_samples,)) for X.
predict_probapredict_proba(X) -> ndarrayReturn posterior class probabilities of shape (n_samples, n_classes).
predict_log_probapredict_log_proba(X) -> ndarrayReturn log-probability estimates of shape (n_samples, n_classes).
predict_joint_log_likelihoodpredict_joint_log_likelihood(X) -> ndarrayReturn unnormalized posterior log-probabilities of shape (n_samples, n_classes).
scorescore(X, y) -> floatReturn mean classification accuracy on (X, y).
savesave(path: str) -> NoneSave the fitted model to a binary .dit file.
loadComplementNB.load(path: str, device: str | None = None) -> ComplementNBLoad a fitted model from a binary .dit file.
toto(device: str) -> ComplementNBMove estimator compute target to another hardware device.

Example

import numpy as np
from ochreml.naive_bayes import ComplementNB

# Imbalanced count dataset (class 0 has 4 samples, class 1 has 1 sample)
X = np.array([
    [4, 1, 0, 0],
    [3, 2, 0, 0],
    [5, 0, 1, 0],
    [3, 1, 0, 0],
    [0, 0, 4, 3],
], dtype=np.float64)
y = np.array([0, 0, 0, 0, 1], dtype=np.float64)

clf = ComplementNB(alpha=1.0, norm=True)
clf.fit(X, y)

X_test = np.array([[4, 1, 0, 0], [0, 0, 3, 2]], dtype=np.float64)
print("Predictions:", clf.predict(X_test))
print("Probabilities:\n", clf.predict_proba(X_test))

On this page