---
title: "MLPClassifier in JavaScript"
description: "Train multi-layer perceptron classifiers in JavaScript and TypeScript with MLPClassifier from @kanaries/ml using Adam or SGD in browser and Node.js."
canonical_url: "https://ml.kanaries.net/docs/apis/neural_network/mlpClassifier"
markdown_url: "https://ml.kanaries.net/docs/apis/neural_network/mlpClassifier.md"
---
# MLPClassifier in JavaScript

## 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`](/docs/apis/pipeline/index.html.md) and [`toJSON()` / `loadModel()`](/docs/apis/serialization/index.html.md).

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: Python and JavaScript / TypeScript

The Python example uses scikit-learn; the TypeScript example uses @kanaries/ml in browser or Node.js runtimes.

#### Python (scikit-learn)

```python
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)

```ts
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

```ts
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

```ts
new NeuralNetwork.MLPClassifier(props?: MLPClassifierProps)
```

### Constructor options

| Option                           | Type                                           | Default                  | Description                                                                          |
| -------------------------------- | ---------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------ |
| `hiddenLayerSizes`               | `number[]`                                     | `[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.                                  |
| `alpha`                          | `number`                                       | `1e-4`                   | L2 regularization strength applied to weights (not biases).                          |
| `batchSize`                      | `number \| 'auto'`                             | `'auto'`                 | Minibatch size; `'auto'` uses `Math.min(200, nSamples)`.                             |
| `learningRate`                   | `'constant' \| 'invscaling' \| 'adaptive'`     | `'constant'`             | Learning-rate schedule used when `solver: 'sgd'`.                                    |
| `learningRateInit`               | `number`                                       | `1e-3`                   | Initial step size for `adam` or `sgd`.                                               |
| `maxIter`                        | `number`                                       | `200`                    | Maximum number of training epochs.                                                   |
| `shuffle`                        | `boolean`                                      | `true`                   | Shuffle training samples at the start of each epoch.                                 |
| `randomState`                    | `number`                                       | `undefined`              | Optional seed for reproducible weight init and shuffling.                            |
| `tol`                            | `number`                                       | `1e-4`                   | Convergence tolerance over `nIterNoChange` epochs.                                   |
| `earlyStopping`                  | `boolean`                                      | `false`                  | Hold out the tail `validationFraction` of rows and restore best validation accuracy. |
| `validationFraction`             | `number`                                       | `0.1`                    | Fraction of training rows reserved when `earlyStopping: true`.                       |
| `momentum` / `nesterovsMomentum` | `number` / `boolean`                           | `0.9` / `true`           | Momentum parameters for `solver: 'sgd'`.                                             |
| `beta1` / `beta2` / `epsilon`    | `number`                                       | `0.9` / `0.999` / `1e-8` | Exponential decay and stability parameters for `solver: 'adam'`.                     |
| `nIterNoChange`                  | `number`                                       | `10`                     | Patience 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](/docs/apis/serialization/index.html.md) 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`](/docs/apis/pipeline/index.html.md) and wrap heavy browser fits with [`utils.asyncMode`](/docs/apis/utils/asyncMode.md).
