SKLearner Home | About | Contact | Examples

Configure MLPRegressor "random_state" Parameter

The random_state parameter in scikit-learn’s MLPRegressor controls the randomness of weight and bias initialization, as well as the shuffling of training data.

Multi-layer Perceptron (MLP) is a type of neural network that can be used for regression tasks. The random_state parameter ensures reproducibility of results by fixing the random number generator seed.

Setting random_state to a specific integer value ensures that the same random numbers are generated each time the model is initialized, leading to consistent results across multiple runs.

The default value for random_state is None, which means that a different random seed is used each time the model is run.

In practice, random_state is often set to a fixed integer (e.g., 42) for reproducibility, or to multiple different values to assess the model’s stability.

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 random_state values
random_state_values = [None, 42, 123, 456]
mse_scores = []

for rs in random_state_values:
    mlp = MLPRegressor(hidden_layer_sizes=(100,), max_iter=500, random_state=rs)
    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"random_state={rs}, MSE: {mse:.3f}")

# Calculate variance of MSE scores
mse_variance = np.var(mse_scores)
print(f"Variance of MSE scores: {mse_variance:.6f}")

Running the example gives an output like:

random_state=None, MSE: 128.429
random_state=42, MSE: 139.311
random_state=123, MSE: 118.676
random_state=456, MSE: 132.617
Variance of MSE scores: 55.999839

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 random_state values
  4. Evaluate the mean squared error (MSE) of each model on the test set
  5. Calculate the variance of MSE scores to assess model stability

Some tips for setting random_state:

Issues to consider:



See Also