Skip to Content
OchreML
Kernel, MLP & Gaussian Process

MLPRegressor

Multi-layer Perceptron regressor optimizing squared error with Adam, SGD, or L-BFGS and incremental partial_fit support.

Overview

MLPRegressor is a classical feed-forward Multi-layer Perceptron regressor optimizing squared error loss with an identity output layer using Adam, SGD with momentum, or L-BFGS. It supports both 1D and 2D multi-output regression targets and provides online / incremental learning via partial_fit(X, y) for streaming minibatches. (o´∀`o)

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) 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 MLPRegressor
# Also available from top-level: from ochreml import MLPRegressor

MLPRegressor(
    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
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 squared-error training loss 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 target outputs.
out_activation_str | NoneName of the output layer activation ("identity").
n_features_in_int | NoneNumber of features seen during fitting.
device_str | NoneResolved execution device string.

Methods

MethodSignatureDescription
fitfit(X, y) -> MLPRegressorFit the MLP regressor to feature matrix X and 1D or 2D target y.
partial_fitpartial_fit(X, y) -> MLPRegressorPerform a single incremental training iteration over (X, y).
predictpredict(X) -> ndarrayPredict target values for samples in X (1D for single output, 2D for multi-output).
scorescore(X, y) -> floatReturn the coefficient of determination (R^2) on (X, y).
toto(device) -> MLPRegressorMove the estimator's compute target to another device.
savesave(path) -> NoneSave the fitted model to a .dit binary file.
loadMLPRegressor.load(path, device=None) -> MLPRegressorClass method to load a fitted model from a .dit file.

Example

import numpy as np
from ochreml.neural_network import MLPRegressor

rng = np.random.default_rng(7)
X = np.linspace(-2.0, 2.0, 120).reshape(-1, 1)
y = X[:, 0] ** 2 - 0.5 * X[:, 0] + 0.05 * rng.normal(size=120)

# Standard batch training
reg = MLPRegressor(hidden_layer_sizes=(32, 16), activation="tanh", solver="adam", max_iter=400, random_state=7)
reg.fit(X, y)
print("Batch R^2:", reg.score(X, y))

# Incremental streaming training with partial_fit
online_reg = MLPRegressor(hidden_layer_sizes=(32,), activation="relu", solver="adam", random_state=7)
for _ in range(20):
    for start in range(0, len(X), 30):
        online_reg.partial_fit(X[start : start + 30], y[start : start + 30])
print("Online predictions (first 3):", online_reg.predict(X[:3]))

On this page