SKLearner Home | About | Contact | Examples

Configure MLPRegressor "momentum" Parameter

The momentum parameter in scikit-learn’s MLPRegressor controls the contribution of the previous gradient step to the current update.

MLPRegressor is a multi-layer perceptron regressor that uses backpropagation for training. It’s suitable for modeling non-linear relationships in regression tasks.

Momentum helps accelerate gradients in the relevant direction and dampens oscillations. It can improve convergence speed and help overcome local optima.

The default value for momentum is 0.9. Common values range from 0.0 (no momentum) to 0.99, with 0.9 being a popular choice.

from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np

# Generate synthetic dataset
X, y = make_regression(n_samples=1000, n_features=10, noise=0.1, random_state=42)

# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train with different momentum values
momentum_values = [0.0, 0.5, 0.9, 0.99]
mse_scores = []

for m in momentum_values:
    mlp = MLPRegressor(hidden_layer_sizes=(100,), max_iter=1000, momentum=m, random_state=42)
    mlp.fit(X_train, y_train)
    y_pred = mlp.predict(X_test)
    mse = mean_squared_error(y_test, y_pred)
    mse_scores.append(mse)
    print(f"momentum={m}, MSE: {mse:.3f}")

# Find best momentum value
best_momentum = momentum_values[np.argmin(mse_scores)]
print(f"Best momentum value: {best_momentum}")

Running the example gives an output like:

momentum=0.0, MSE: 30.530
momentum=0.5, MSE: 30.530
momentum=0.9, MSE: 30.530
momentum=0.99, MSE: 30.530
Best momentum value: 0.0

The key steps in this example are:

  1. Generate a synthetic regression dataset
  2. Split the data into train and test sets
  3. Train MLPRegressor models with different momentum values
  4. Evaluate the mean squared error (MSE) of each model on the test set
  5. Identify the best performing momentum value

Some tips and heuristics for setting momentum:

Issues to consider:



See Also