Skip to Content
OchreML
Kernel, MLP & Gaussian Process

MLPClassifier

Multi-layer Perceptron classifier optimizing log-loss with Adam, SGD, or L-BFGS and incremental partial_fit support.

Overview

MLPClassifier is a classical feed-forward Multi-layer Perceptron classifier optimizing log-loss (binary cross-entropy with logistic output, or multiclass cross-entropy with softmax output) using Adam, SGD with momentum, or L-BFGS. It supports online / incremental learning via partial_fit(X, y, classes=...) for streaming batches that do not fit in memory at once. (^▽^)

Backend Support

  • Primitives: E1 (matmul), E2 (matmul_at_b), N2 (elementwise activations and derivatives)
  • Devices: cpu (Rayon parallel f64), cuda / cuda:0 (dynamic cuBLAS), wgpu (Vulkan/Metal/DX12), tpu (OpenXLA PJRT), and auto
  • Incremental Learning: Supports partial_fit(X, y, classes=None) for single-iteration updates with stochastic solvers ("adam" or "sgd")
  • Persistence: .dit binary format via save() / load() (and ochreml.save() / ochreml.load()), plus Python pickle support

Import & Signature

from ochreml.neural_network import MLPClassifier
# Also available from top-level: from ochreml import MLPClassifier

MLPClassifier(
    hidden_layer_sizes: int | Sequence[int] = (100,),
    activation: str = "relu",
    solver: str = "adam",
    alpha: float = 0.0001,
    batch_size: str | int = "auto",
    learning_rate: str = "constant",
    learning_rate_init: float = 0.001,
    power_t: float = 0.5,
    max_iter: int = 200,
    shuffle: bool = True,
    random_state: int | None = None,
    tol: float = 1e-4,
    momentum: float = 0.9,
    nesterovs_momentum: bool = True,
    early_stopping: bool = False,
    validation_fraction: float = 0.1,
    beta_1: float = 0.9,
    beta_2: float = 0.999,
    epsilon: float = 1e-8,
    n_iter_no_change: int = 10,
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
hidden_layer_sizestuple[int, ...] or int(100,)The i-th element specifies the number of neurons in the i-th hidden layer.
activation{"identity", "logistic", "tanh", "relu"}"relu"Activation function for the hidden layers.
solver{"lbfgs", "sgd", "adam"}"adam"Optimization algorithm for weight updates.
alphafloat0.0001Strength of the L2 regularization penalty.
batch_sizeint or "auto""auto"Size of minibatches for stochastic optimizers ("auto" selects min(200, n_samples)).
learning_rate{"constant", "invscaling", "adaptive"}"constant"Learning rate schedule for weight updates (used when solver="sgd").
learning_rate_initfloat0.001Initial learning rate for "sgd" and "adam".
power_tfloat0.5Exponent for inverse scaling learning rate (learning_rate="invscaling").
max_iterint200Maximum number of training iterations (epochs for stochastic solvers).
shuffleboolTrueWhether to shuffle training samples in each iteration (for "sgd" and "adam").
random_stateint | NoneNoneRandom seed controlling weight initialization, shuffling, and validation split.
tolfloat1e-4Optimization tolerance for stopping when loss or validation score stops improving.
momentumfloat0.9Momentum factor for "sgd" updates (in [0, 1]).
nesterovs_momentumboolTrueWhether to use Nesterov momentum when solver="sgd" and momentum > 0.
early_stoppingboolFalseWhether to hold out a validation split and stop early when validation score stops improving.
validation_fractionfloat0.1Proportion of training data set aside for early stopping validation.
beta_1float0.9Exponential decay rate for first moment estimates in "adam".
beta_2float0.999Exponential decay rate for second moment estimates in "adam".
epsilonfloat1e-8Numerical stability constant in "adam".
n_iter_no_changeint10Maximum number of consecutive epochs without tol improvement before stopping.
devicestr | NoneNoneExecution device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
classes_ndarray of shape (n_classes,)Sorted unique class labels seen during fit() or partial_fit().
coefs_list[ndarray]Weight matrices for each layer in the network.
intercepts_list[ndarray]Bias vectors for each layer in the network.
loss_float | NoneCurrent training loss computed after the final iteration.
loss_curve_list[float]Loss value recorded at each training iteration.
n_iter_intNumber of iterations the solver has run.
n_layers_int | NoneTotal number of layers (input + hidden + output).
n_outputs_int | NoneNumber of output units (1 for binary, n_classes for multiclass).
out_activation_str | NoneName of the output layer activation ("logistic" or "softmax").
n_features_in_int | NoneNumber of features seen during fitting.
device_str | NoneResolved execution device string.

Methods

MethodSignatureDescription
fitfit(X, y) -> MLPClassifierFit the MLP classifier to feature matrix X and labels y.
partial_fitpartial_fit(X, y, classes=None) -> MLPClassifierPerform a single incremental training iteration over (X, y). Pass classes on the first call.
predictpredict(X) -> ndarrayPredict class labels for samples in X.
predict_probapredict_proba(X) -> ndarrayReturn class probability estimates of shape (n_samples, n_classes).
predict_log_probapredict_log_proba(X) -> ndarrayReturn log-probabilities of shape (n_samples, n_classes).
scorescore(X, y) -> floatReturn mean classification accuracy on (X, y).
toto(device) -> MLPClassifierMove the estimator's compute target to another device.
savesave(path) -> NoneSave the fitted model to a .dit binary file.
loadMLPClassifier.load(path, device=None) -> MLPClassifierClass method to load a fitted model from a .dit file.

Example

import numpy as np
from ochreml.neural_network import MLPClassifier

rng = np.random.default_rng(42)
X0 = rng.normal(loc=-1.5, scale=0.6, size=(60, 2))
X1 = rng.normal(loc=1.5, scale=0.6, size=(60, 2))
X = np.vstack([X0, X1])
y = np.array([0.0] * 60 + [1.0] * 60)

# Standard batch training
clf = MLPClassifier(hidden_layer_sizes=(32, 16), activation="relu", solver="adam", max_iter=200, random_state=42)
clf.fit(X, y)
print("Batch accuracy:", clf.score(X, y))
print("Predicted probabilities (first 2):", clf.predict_proba(X[:2]))

# Incremental streaming training with partial_fit
online_clf = MLPClassifier(hidden_layer_sizes=(16,), solver="adam", random_state=42)
for start in range(0, len(X), 30):
    online_clf.partial_fit(X[start : start + 30], y[start : start + 30], classes=[0.0, 1.0])
print("Online accuracy:", online_clf.score(X, y))

On this page