@kanaries/ml
API Reference/Neural Network

MLPRegressor

Train multi-layer perceptron regressors in JavaScript and TypeScript with MLPRegressor from @kanaries/ml using Adam or SGD in browser and Node.js.

View as Markdown

Algorithm overview

MLPRegressor (Multi-Layer Perceptron Regressor) fits a feedforward neural network to predict continuous numeric targets by minimizing squared error loss with minibatch backpropagation. Hidden layers with nonlinear activations (relu, tanh, or logistic) enable smooth curve approximation and multi-feature interaction modeling without manually engineering polynomial cross-terms.

An MLP regressor is well suited when:

  • The target responds nonlinearly to combinations of continuous features.
  • Linear, Ridge, or low-degree polynomial regression leaves systematic residual structure.
  • You want a compact, serializable neural regressor that trains and predicts directly in JavaScript without deploying a Python inference service or GPU runtime.

JavaScript implementation

@kanaries/ml implements MLPRegressor in pure TypeScript under the NeuralNetwork namespace for browsers, Node.js, and edge runtimes. It follows scikit-learn's stochastic optimization path (adam and sgd solvers, Glorot uniform initialization, L2 weight decay alpha, and optional early stopping tracked on validation R²) and supports portable JSON persistence via toJSON() / loadModel().

Because gradient-based networks are sensitive to feature scale, wrap MLPRegressor behind utils.Preprocessing.StandardScaler in a Pipeline whenever input columns have different units or ranges.

Quick start

MLPRegressor in Python vs JavaScript / TypeScript

If you searched for "MLPRegressor in JavaScript" or "MLPRegressor in TypeScript", this section maps the familiar scikit-learn call to the equivalent @kanaries/ml usage for browser and Node.js runtimes.

Python
scikit-learn
from sklearn.neural_network import MLPRegressor

X = [[-2.0], [-1.0], [0.0], [1.0], [2.0], [3.0]]
y = [4.0, 1.0, 0.0, 1.0, 4.0, 9.0]

reg = MLPRegressor(hidden_layer_sizes=(16,), activation='relu', max_iter=500, random_state=42)
reg.fit(X, y)
print(reg.predict([[1.5], [2.5]]))
JavaScript / TypeScript
@kanaries/ml
import { NeuralNetwork } from '@kanaries/ml';

const X = [[-2.0], [-1.0], [0.0], [1.0], [2.0], [3.0]];
const y = [4.0, 1.0, 0.0, 1.0, 4.0, 9.0];

const reg = new NeuralNetwork.MLPRegressor({
hiddenLayerSizes: [16],
activation: 'relu',
learningRateInit: 0.02,
maxIter: 500,
randomState: 42,
});
reg.fit(X, y);
console.log(reg.predict([[1.5], [2.5]]));

Quick JavaScript example

import { NeuralNetwork } from '@kanaries/ml';

const X = [[-2.0], [-1.0], [0.0], [1.0], [2.0], [3.0]];
const y = [4.0, 1.0, 0.0, 1.0, 4.0, 9.0];

const reg = new NeuralNetwork.MLPRegressor({
  hiddenLayerSizes: [16],
  activation: 'relu',
  solver: 'adam',
  learningRateInit: 0.02,
  maxIter: 500,
  randomState: 42,
});

reg.fit(X, y);
const predictions = reg.predict([[1.5], [2.5]]);
console.log({ predictions, finalLoss: reg.lossCurve.at(-1), nIter: reg.nIter });

Detailed API reference

new NeuralNetwork.MLPRegressor(props?: MLPRegressorProps)

Constructor options

OptionTypeDefaultDescription
hiddenLayerSizesnumber[][100]Neuron counts for each hidden layer, e.g. [32, 16].
activation'identity' | 'logistic' | 'tanh' | 'relu''relu'Activation applied after each hidden layer.
solver'adam' | 'sgd''adam'Stochastic optimizer (lbfgs is not implemented).
alphanumber1e-4L2 penalty strength applied to layer weights.
batchSizenumber | 'auto''auto'Minibatch size; 'auto' uses Math.min(200, nSamples).
learningRate'constant' | 'invscaling' | 'adaptive''constant'Step-size schedule for solver: 'sgd'.
learningRateInitnumber1e-3Initial learning rate.
maxIternumber200Maximum number of training epochs.
shufflebooleantrueShuffle samples each epoch during training.
randomStatenumberundefinedOptional seed for reproducible training.
tolnumber1e-4Improvement tolerance over nIterNoChange epochs.
earlyStoppingbooleanfalseReserve the tail validationFraction of rows and keep weights with highest validation R².
validationFractionnumber0.1Validation fraction when earlyStopping: true.
momentum / nesterovsMomentumnumber / boolean0.9 / trueSGD momentum settings.
beta1 / beta2 / epsilonnumber0.9 / 0.999 / 1e-8Adam optimizer hyperparameters.
nIterNoChangenumber10Patience epochs without improvement before early stop.

Methods and properties

  • fit(trainX: number[][], trainY: number[]): void — fits a single continuous target with identity output activation and squared loss mean((y - p)^2) / 2.
  • predict(testX: number[][]): number[] — returns continuous predictions for each input row.
  • lossCurve: number[], nIter: number — inspect training convergence and epochs completed.
  • getParams(), setParams(), clone(), toJSON() — compatible with Pipeline, ModelSelection, and loadModel().

scikit-learn compatibility notes

  • Supports single-target regression (y: number[]); for correlated multi-target regression, wrap with MultiOutput.RegressorChain or MultiOutputRegressor.
  • Only 'adam' and 'sgd' solvers are implemented ('lbfgs' is omitted).
  • Early stopping uses a deterministic tail holdout split rather than a shuffled split; shuffle rows before fit() if your dataset is sorted.