SKLearner Home | About | Contact | Examples

Scikit-Learn MLPClassifier Model

MLPClassifier is a powerful neural network model in scikit-learn for classification tasks. It can handle complex non-linear relationships between input features and target classes.

The key hyperparameters of MLPClassifier include hidden_layer_sizes (the number of neurons in each hidden layer), activation (the activation function), solver (the optimization algorithm), and alpha (the L2 regularization term).

The algorithm is suitable for both binary and multi-class classification problems.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score

# generate multi-class classification dataset
X, y = make_classification(n_samples=100, n_clusters_per_class=1, n_features=5, n_classes=3, 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 = MLPClassifier()

# fit model
model.fit(X_train, y_train)

# evaluate model
yhat = model.predict(X_test)
acc = accuracy_score(y_test, yhat)
print('Accuracy: %.3f' % acc)

# make a prediction
row = [[-1.10325445, -0.49821356, -0.05962247, -0.89224592, -0.70158632]]
yhat = model.predict(row)
print('Predicted: %d' % yhat[0])

Running the example gives an output like:

Accuracy: 1.000
Predicted: 2

The steps in this example are:

  1. A synthetic multi-class classification dataset is generated using make_classification() with a specified number of samples, features, classes, and a fixed random seed for reproducibility. The dataset is then split into training and test sets using train_test_split().

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

  3. The model’s performance is evaluated by comparing the predictions (yhat) to the actual values (y_test) using the accuracy score metric.

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

This example showcases how to quickly set up and use an MLPClassifier model for multi-class classification tasks in scikit-learn. The model can learn complex non-linear relationships and provide accurate predictions with minimal setup.



See Also