@kanaries/ml
API Reference/Neural Network

MLPClassifier

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

View as Markdown

Algorithm overview

MLPClassifier (Multi-Layer Perceptron Classifier) is a feedforward neural network trained with minibatch backpropagation and cross-entropy loss. Unlike linear classifiers that separate classes with a single hyperplane, one or more hidden layers with nonlinear activations (relu, tanh, or logistic) allow an MLP to learn curved, interacting decision boundaries directly from tabular features.

An MLP classifier is a strong fit when:

  • Your numeric features have nonlinear interactions that linear or logistic regression cannot separate cleanly.
  • You want calibrated probability estimates via predictProba() for binary or multiclass targets.
  • Your dataset is tabular and moderate in size, where a lightweight neural network trains in milliseconds without requiring a GPU tensor framework.

JavaScript implementation

@kanaries/ml ships a pure TypeScript implementation of MLPClassifier under the NeuralNetwork namespace that runs in browsers, Node.js, and serverless edge runtimes with zero native dependencies. It mirrors scikit-learn's stochastic training path (adam and sgd solvers, Glorot uniform initialization, L2 weight regularization alpha, learning-rate schedules, and early stopping) while integrating cleanly with Pipeline and toJSON() / loadModel().

Always standardize continuous input features with utils.Preprocessing.StandardScaler before fitting MLPClassifier so gradients stay well-conditioned across columns of different magnitudes.

Quick start

MLPClassifier in Python vs JavaScript / TypeScript

If you searched for "MLPClassifier in JavaScript" or "MLPClassifier 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 MLPClassifier

X = [
  [-1.2, -1.0], [-0.9, -1.3], [1.1, 1.2], [1.3, 0.9],
  [-1.1, 1.2], [-1.3, 0.8], [1.0, -1.1], [1.2, -0.9],
]
y = [0, 0, 0, 0, 1, 1, 1, 1]

clf = MLPClassifier(hidden_layer_sizes=(8,), activation='relu', max_iter=300, random_state=42)
clf.fit(X, y)
print(clf.predict([[1.0, 1.0], [-1.0, 1.0]]))
JavaScript / TypeScript
@kanaries/ml
import { NeuralNetwork } from '@kanaries/ml';

const X = [
[-1.2, -1.0], [-0.9, -1.3], [1.1, 1.2], [1.3, 0.9],
[-1.1, 1.2], [-1.3, 0.8], [1.0, -1.1], [1.2, -0.9],
];
const y = [0, 0, 0, 0, 1, 1, 1, 1];

const clf = new NeuralNetwork.MLPClassifier({
hiddenLayerSizes: [8],
activation: 'relu',
maxIter: 300,
randomState: 42,
});
clf.fit(X, y);
console.log(clf.predict([[1.0, 1.0], [-1.0, 1.0]]));

Quick JavaScript example

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

const X = [
  [-1.2, -1.0], [-0.9, -1.3], [1.1, 1.2], [1.3, 0.9],
  [-1.1, 1.2], [-1.3, 0.8], [1.0, -1.1], [1.2, -0.9],
];
const y = [0, 0, 0, 0, 1, 1, 1, 1];

const clf = new NeuralNetwork.MLPClassifier({
  hiddenLayerSizes: [8],
  activation: 'relu',
  solver: 'adam',
  learningRateInit: 0.02,
  maxIter: 300,
  randomState: 42,
});

clf.fit(X, y);
const predictions = clf.predict([[1.0, 1.0], [-1.0, 1.0]]);
const probabilities = clf.predictProba([[1.0, 1.0], [-1.0, 1.0]]);
console.log({ predictions, probabilities, nIter: clf.nIter });

Detailed API reference

new NeuralNetwork.MLPClassifier(props?: MLPClassifierProps)

Constructor options

OptionTypeDefaultDescription
hiddenLayerSizesnumber[][100]Number of neurons in each hidden layer, e.g. [32, 16].
activation'identity' | 'logistic' | 'tanh' | 'relu''relu'Hidden layer activation function.
solver'adam' | 'sgd''adam'Weight optimizer. Note: lbfgs is not implemented.
alphanumber1e-4L2 regularization strength applied to weights (not biases).
batchSizenumber | 'auto''auto'Minibatch size; 'auto' uses Math.min(200, nSamples).
learningRate'constant' | 'invscaling' | 'adaptive''constant'Learning-rate schedule used when solver: 'sgd'.
learningRateInitnumber1e-3Initial step size for adam or sgd.
maxIternumber200Maximum number of training epochs.
shufflebooleantrueShuffle training samples at the start of each epoch.
randomStatenumberundefinedOptional seed for reproducible weight init and shuffling.
tolnumber1e-4Convergence tolerance over nIterNoChange epochs.
earlyStoppingbooleanfalseHold out the tail validationFraction of rows and restore best validation accuracy.
validationFractionnumber0.1Fraction of training rows reserved when earlyStopping: true.
momentum / nesterovsMomentumnumber / boolean0.9 / trueMomentum parameters for solver: 'sgd'.
beta1 / beta2 / epsilonnumber0.9 / 0.999 / 1e-8Exponential decay and stability parameters for solver: 'adam'.
nIterNoChangenumber10Patience epochs without improvement before stopping early.

Methods and properties

  • fit(trainX: number[][], trainY: number[]): void — trains binary (single sigmoid output) or multiclass (softmax output) weights.
  • predict(testX: number[][]): number[] — returns predicted class labels.
  • predictProba(testX: number[][]): number[][] — returns per-class probabilities ordered by clf.classes.
  • classes: number[], lossCurve: number[], nIter: number — inspect learned class labels, per-epoch loss, and completed epochs.
  • getParams(), setParams(), clone(), toJSON() — full @kanaries/ml estimator contract for Pipeline and portable JSON deployment.

scikit-learn compatibility notes

  • Only stochastic solvers ('adam' and 'sgd') are supported; 'lbfgs' is omitted to keep the bundle small.
  • When earlyStopping: true, @kanaries/ml holds out the deterministic tail validationFraction of rows rather than a shuffled stratified split. Shuffle your dataset before fitting if rows are ordered by class.
  • Pair MLPClassifier with utils.Preprocessing.StandardScaler inside a Pipeline and wrap heavy browser fits with utils.asyncMode.