SKLearner Home | About | Contact | Examples

Scikit-Learn RandomizedSearchCV MLPRegressor

Hyperparameter tuning is essential for optimizing machine learning models. In this example, we’ll demonstrate how to use scikit-learn’s RandomizedSearchCV for hyperparameter tuning of an MLPRegressor model, commonly used for regression tasks.

Random search is a method for evaluating different combinations of model hyperparameters. Unlike grid search, it samples a fixed number of hyperparameter combinations from a specified distribution, making it more efficient when searching over a large hyperparameter space.

MLPRegressor is a multi-layer perceptron (neural network) model used for regression tasks. It can model complex relationships by learning from data through backpropagation.

Key hyperparameters for MLPRegressor include the size of the hidden layers (hidden_layer_sizes), which determines the number of neurons in each hidden layer; the activation function (activation), which can be 'relu', 'tanh', etc.; the solver (solver), which specifies the optimization algorithm ('adam', 'lbfgs', etc.); the regularization term (alpha) to prevent overfitting; and the learning rate schedule (learning_rate).

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.neural_network import MLPRegressor
from scipy.stats import uniform, randint

# Generate synthetic regression dataset
X, y = make_regression(n_samples=100, n_features=20, 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)

# Define the model
model = MLPRegressor(random_state=42)

# Define hyperparameter distribution
param_dist = {
    'hidden_layer_sizes': [(50,), (100,), (100, 50), (50, 25)],
    'activation': ['relu', 'tanh'],
    'solver': ['adam', 'lbfgs'],
    'alpha': uniform(0.0001, 0.01),
    'learning_rate': ['constant', 'adaptive']
}

# Perform random search
random_search = RandomizedSearchCV(estimator=model,
                                   param_distributions=param_dist,
                                   n_iter=50,
                                   cv=5,
                                   scoring='neg_mean_squared_error',
                                   random_state=42)
random_search.fit(X_train, y_train)

# Report best score and parameters
print(f"Best score: {random_search.best_score_:.3f}")
print(f"Best parameters: {random_search.best_params_}")

# Evaluate on test set
best_model = random_search.best_estimator_
test_score = best_model.score(X_test, y_test)
print(f"Test set R^2 score: {test_score:.3f}")

Running the example gives an output like:

Best score: -894.166
Best parameters: {'activation': 'relu', 'alpha': 0.007206628896857874, 'hidden_layer_sizes': (100,), 'learning_rate': 'adaptive', 'solver': 'lbfgs'}
Test set R^2 score: 0.993

The steps are as follows:

  1. Generate a synthetic regression dataset using make_regression.
  2. Split the dataset into training and testing sets using train_test_split.
  3. Define the MLPRegressor model.
  4. Specify the hyperparameter distributions, including hidden_layer_sizes, activation, solver, alpha, and learning_rate.
  5. Use RandomizedSearchCV to perform random search, specifying the model, hyperparameter distributions, 50 iterations, 5-fold cross-validation, and a negative mean squared error scoring metric.
  6. Report the best cross-validation score and hyperparameters found by random search.
  7. Evaluate the best model on the hold-out test set and report the R^2 score.

By using RandomizedSearchCV, we can efficiently explore various hyperparameter configurations and identify the optimal settings for the MLPRegressor, enhancing the model’s performance on regression tasks.



See Also