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 parallelf64),cuda/cuda:0(dynamic cuBLAS),wgpu(Vulkan/Metal/DX12),tpu(OpenXLA PJRT), andauto - Incremental Learning: Supports
partial_fit(X, y, classes=None)for single-iteration updates with stochastic solvers ("adam"or"sgd") - Persistence:
.ditbinary format viasave()/load()(andochreml.save()/ochreml.load()), plus Pythonpicklesupport
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
| Parameter | Type | Default | Description |
|---|---|---|---|
hidden_layer_sizes | tuple[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. |
alpha | float | 0.0001 | Strength of the L2 regularization penalty. |
batch_size | int 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_init | float | 0.001 | Initial learning rate for "sgd" and "adam". |
power_t | float | 0.5 | Exponent for inverse scaling learning rate (learning_rate="invscaling"). |
max_iter | int | 200 | Maximum number of training iterations (epochs for stochastic solvers). |
shuffle | bool | True | Whether to shuffle training samples in each iteration (for "sgd" and "adam"). |
random_state | int | None | None | Random seed controlling weight initialization, shuffling, and validation split. |
tol | float | 1e-4 | Optimization tolerance for stopping when loss or validation score stops improving. |
momentum | float | 0.9 | Momentum factor for "sgd" updates (in [0, 1]). |
nesterovs_momentum | bool | True | Whether to use Nesterov momentum when solver="sgd" and momentum > 0. |
early_stopping | bool | False | Whether to hold out a validation split and stop early when validation score stops improving. |
validation_fraction | float | 0.1 | Proportion of training data set aside for early stopping validation. |
beta_1 | float | 0.9 | Exponential decay rate for first moment estimates in "adam". |
beta_2 | float | 0.999 | Exponential decay rate for second moment estimates in "adam". |
epsilon | float | 1e-8 | Numerical stability constant in "adam". |
n_iter_no_change | int | 10 | Maximum number of consecutive epochs without tol improvement before stopping. |
device | str | None | None | Execution device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device(). |
Attributes
| Attribute | Type | Description |
|---|---|---|
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 | None | Current training loss computed after the final iteration. |
loss_curve_ | list[float] | Loss value recorded at each training iteration. |
n_iter_ | int | Number of iterations the solver has run. |
n_layers_ | int | None | Total number of layers (input + hidden + output). |
n_outputs_ | int | None | Number of output units (1 for binary, n_classes for multiclass). |
out_activation_ | str | None | Name of the output layer activation ("logistic" or "softmax"). |
n_features_in_ | int | None | Number of features seen during fitting. |
device_ | str | None | Resolved execution device string. |
Methods
| Method | Signature | Description |
|---|---|---|
fit | fit(X, y) -> MLPClassifier | Fit the MLP classifier to feature matrix X and labels y. |
partial_fit | partial_fit(X, y, classes=None) -> MLPClassifier | Perform a single incremental training iteration over (X, y). Pass classes on the first call. |
predict | predict(X) -> ndarray | Predict class labels for samples in X. |
predict_proba | predict_proba(X) -> ndarray | Return class probability estimates of shape (n_samples, n_classes). |
predict_log_proba | predict_log_proba(X) -> ndarray | Return log-probabilities of shape (n_samples, n_classes). |
score | score(X, y) -> float | Return mean classification accuracy on (X, y). |
to | to(device) -> MLPClassifier | Move the estimator's compute target to another device. |
save | save(path) -> None | Save the fitted model to a .dit binary file. |
load | MLPClassifier.load(path, device=None) -> MLPClassifier | Class 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))