SKLearner Home | About | Contact | Examples

Scikit-Learn MLPRegressor Model

MLPRegressor is a powerful neural network model for regression tasks in scikit-learn. It can learn complex non-linear relationships between input features and target values.

The key hyperparameters of MLPRegressor include hidden_layer_sizes (the number of neurons in each hidden layer), activation (the activation function), solver (the optimization algorithm), alpha (the L2 regularization strength), and learning_rate_init (the initial learning rate).

This algorithm is suitable for a wide range of regression problems where the relationship between inputs and outputs is not necessarily linear.

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

# generate regression dataset
X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state=1)

# 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=1)

# create model
model = MLPRegressor()

# fit model
model.fit(X_train, y_train)

# evaluate model
yhat = model.predict(X_test)
mse = mean_squared_error(y_test, yhat)
print('MSE: %.3f' % mse)

# make a prediction
row = [[0.59332206, -0.56637507, 0.34669445, 0.37237591, -2.08707514]]
yhat = model.predict(row)
print('Prediction: %.3f' % yhat[0])

Running the example gives an output like:

MSE: 4593.176
Prediction: -8.862

The steps are as follows:

  1. A synthetic regression dataset is generated using make_regression(). This function creates a dataset with a specified number of samples (n_samples), features (n_features), noise level (noise), and a fixed random seed (random_state) for reproducibility. The dataset is then split into training and test sets using train_test_split().

  2. An MLPRegressor model is instantiated with default hyperparameters. The model is then fit on the training data using the fit() method.

  3. The performance of the model is evaluated by comparing the predictions (yhat) to the actual values (y_test) using the mean squared error metric.

  4. A single prediction can be made by passing a new data sample to the predict() method.

This example demonstrates how to set up and use an MLPRegressor model for regression tasks in scikit-learn. The model can learn complex non-linear relationships and provide predictions on new data.



See Also