Neural Networks with MLP
A single perceptron can only draw straight lines. Connect many neurons in layers and the network can learn curved, complex boundaries. The classic architecture is the multi-layer perceptron (MLP):
input layer -> hidden layer(s) -> output layer
(features) (neurons with (one neuron per class,
ReLU activation) or one for regression)Every neuron in a layer is connected to every neuron in the next ("fully connected" or "dense" layers). Training adjusts all the weights with gradient descent: compute how wrong the output is (the loss), use backpropagation to find how each weight contributed to that error, and nudge every weight a little in the direction that reduces it.
scikit-learn includes MLPClassifier and MLPRegressor — great for learning and for small to medium tabular problems.
Solving XOR
The problem a single perceptron could not solve takes one small hidden layer:
import numpy as np
from sklearn.neural_network import MLPClassifier
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
mlp = MLPClassifier(hidden_layer_sizes=(4,), activation="tanh", solver="lbfgs",
max_iter=1000, random_state=1)
mlp.fit(X, y)
print("predictions:", mlp.predict(X), " target:", y)
print("weight shapes:", [w.shape for w in mlp.coefs_])
print("P(1):", mlp.predict_proba(X)[:, 1].round(3))predictions: [0 1 1 0] target: [0 1 1 0]
weight shapes: [(2, 4), (4, 1)]
P(1): [0. 0.999 1. 0.001]
The weight shapes tell the architecture: a 2×4 matrix from the 2 inputs to the 4 hidden neurons, and a 4×1 matrix from the hidden layer to the output. The hidden neurons learn intermediate features (roughly "at least one input is on" and "both are on") that make XOR separable for the output neuron.
Curved decision boundaries
On the two-moons data the MLP learns a smooth curved boundary:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = make_moons(n_samples=300, noise=0.25, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(16, 16), max_iter=2000, random_state=0).fit(X_tr, y_tr)
print(f"train accuracy {mlp.score(X_tr, y_tr):.3f}, test accuracy {mlp.score(X_te, y_te):.3f}")
print("training stopped after", mlp.n_iter_, "epochs")
xx, yy = np.meshgrid(np.linspace(-2, 3, 200), np.linspace(-1.5, 2, 200))
zz = mlp.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1].reshape(xx.shape)
plt.contourf(xx, yy, zz, levels=20, cmap="coolwarm", alpha=0.6)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", edgecolors="k", s=15)
plt.show()train accuracy 0.867, test accuracy 0.856
training stopped after 261 epochs
hidden_layer_sizes=(16, 16) means two hidden layers with 16 neurons each. The default solver, adam, is a popular variant of gradient descent that adapts the step size per weight.
Scale your inputs
Neural networks are trained with gradient descent, which struggles when features have very different scales (the breast-cancer features range from below 0.01 to over 1 000). Compare an MLP on the raw breast-cancer features with one in a pipeline after StandardScaler:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
raw = MLPClassifier(hidden_layer_sizes=(32,), max_iter=3000, random_state=0).fit(X_tr, y_tr)
scaled = make_pipeline(StandardScaler(),
MLPClassifier(hidden_layer_sizes=(32,), max_iter=3000, random_state=0)).fit(X_tr, y_tr)
print(f"raw features: test accuracy {raw.score(X_te, y_te):.3f}")
print(f"scaled features: test accuracy {scaled.score(X_te, y_te):.3f}")raw features: test accuracy 0.942
scaled features: test accuracy 0.953
Here the adam optimiser copes reasonably well even with raw inputs, and scaling still improves the test accuracy. On many data sets the difference is much larger: unscaled inputs can make training crawl or stall completely. Scaling costs nothing, so always do it.
Watching training: the loss curve
With the adam or sgd solver, loss_curve_ records the training loss after every epoch. early_stopping=True holds out 10 % of the training data and stops when the validation score stops improving:
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
mlp = MLPClassifier(hidden_layer_sizes=(64,), alpha=1e-3, early_stopping=True,
max_iter=500, random_state=0)
model = make_pipeline(StandardScaler(), mlp).fit(X_tr, y_tr)
plt.plot(mlp.loss_curve_, label="training loss")
plt.plot(mlp.validation_scores_, label="validation accuracy")
plt.xlabel("epoch")
plt.legend()
plt.show()
print("epochs run:", mlp.n_iter_)
print(f"best validation accuracy: {mlp.best_validation_score_:.3f}")
print(f"test accuracy: {model.score(X_te, y_te):.3f}")epochs run: 41
best validation accuracy: 0.960
test accuracy: 0.957
Key hyperparameters
| Parameter | Meaning | Tips |
|---|---|---|
hidden_layer_sizes |
neurons per hidden layer, e.g. (64,) or (64, 32) |
start small; widen/deepen if underfitting |
activation |
"relu" (default), "tanh", "logistic" |
relu is a safe default |
alpha |
L2 regularization strength | increase if overfitting |
learning_rate_init |
step size for adam/sgd | 1e-3 default; too high diverges |
max_iter |
maximum epochs | raise it if you see a ConvergenceWarning |
early_stopping |
stop when validation stops improving | good default for adam/sgd |
Note: scikit-learn's MLP runs on the CPU and has no convolutional or recurrent layers. For images, audio, text and large data, use a deep-learning framework (next lesson). For typical spreadsheet-style data, gradient-boosted trees are usually stronger than MLPs anyway.
Go further: Neurons, Layers and the Forward Pass opens the Deep Learning course, which builds networks like this one in NumPy and then in PyTorch.
Test yourself
What does hidden_layer_sizes=(32, 16) create?
- One layer with 48 neurons
- Two hidden layers with 32 and 16 neurons
- 32 networks with 16 layers
- A network with 32 inputs
Why can an MLP solve XOR when a single perceptron can't?
- It trains for longer
- Its hidden layer creates new features that make the problem linearly separable
- It uses a larger learning rate
- It memorises the data
What does backpropagation compute?
- The predictions of the network
- How much each weight contributed to the error (the gradients)
- The best number of layers
- The training data