“A neural network is logistic regression, stacked. Knowing whether it works is a whole skill of its own.”
This post closes Module 2 with two things that belong together. The first is the ninth supervised algorithm, the artificial neural network (ANN), the idea behind everything from image recognition to ChatGPT. The second is the question every previous post has been circling: how do you know a model is actually good?
We will build a small neural network from scratch in NumPy, train a bigger one with scikit-learn, and then watch one memorise noise. That leads straight into evaluation: the bias–variance trade-off, regularization, cross-validation, the accuracy trap, and the confusion matrix with precision, recall and F1. If you only remember one post from this module, make it this one.
One neuron: weigh, add, squash

An artificial neuron does three things:
- Weigh each input: multiply x₁, x₂, x₃ by weights w₁, w₂, w₃.
- Add them up with a bias: z = w₁x₁ + w₂x₂ + w₃x₃ + b.
- Squash the result through an activation function: ŷ = g(z).
If g is the sigmoid, this neuron is exactly the logistic regression from Ep02. Same weights, same bias, same S-curve. A neural network is many of these neurons arranged in layers, each layer feeding the next.
The activation function is what makes layers worth stacking. The common ones:
- ReLU, max(0, z): passes positive values through and zeroes out negatives. Cheap, trains fast, and the default for hidden layers.
- Sigmoid, 1 / (1 + e⁻ᶻ): squashes to 0–1. Used on the output for binary classification.
- Softmax: turns several outputs into probabilities that add up to 1. Used on the output for multi-class classification.
- tanh: like sigmoid but from −1 to 1, common inside recurrent networks (Ep13).
Without a non-linear activation, stacking layers would be pointless: a chain of linear functions is still just one linear function.
Why one neuron isn’t enough: XOR
The classic proof is XOR: output 1 when exactly one of two inputs is 1. Plot the four cases and the two 1s sit on opposite corners of a square. No single straight line separates them, so a single neuron (or logistic regression) can never learn it. Add one hidden layer and the network can bend its boundary to fit.
Step 1: A neural network from scratch
Here is a network with 2 inputs, 4 hidden neurons and 1 output, trained on XOR with nothing but NumPy:
import numpy as np
# XOR: output is 1 only when exactly one input is 1. No straight line separates it.
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
rng = np.random.default_rng(1)
W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros((1, 4)) # input -> 4 hidden neurons
W2, b2 = rng.normal(0, 1, (4, 1)), np.zeros((1, 1)) # hidden -> 1 output
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0
for epoch in range(5001):
# forward pass
h = sigmoid(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
loss = ((out - y) ** 2).mean()
# backward pass (chain rule, layer by layer)
d_out = (out - y) * out * (1 - out)
d_h = (d_out @ W2.T) * h * (1 - h)
W2 -= lr * h.T @ d_out; b2 -= lr * d_out.sum(axis=0, keepdims=True)
W1 -= lr * X.T @ d_h; b1 -= lr * d_h.sum(axis=0, keepdims=True)
if epoch in (0, 1000, 5000):
print(f"epoch {epoch:>4}: loss = {loss:.4f}")
print("predictions:", out.ravel().round(3))
Output:
epoch 0: loss = 0.2749
epoch 1000: loss = 0.0023
epoch 5000: loss = 0.0002
predictions: [0.012 0.984 0.986 0.019]
What’s actually happening here
The predictions for (0,0), (0,1), (1,0), (1,1) end up at 0.012, 0.984, 0.986 and 0.019: XOR, learned. Each loop has two halves:
- Forward pass. Inputs flow through the hidden layer (
h) to the output (out), exactly like stacked logistic regressions. - Backward pass. The error at the output is pushed back through the network with the chain rule.
d_outis the output error times the sigmoid’s slope, out × (1 − out);d_hsends that error back throughW2to work out how much each hidden neuron contributed. Every weight then takes a gradient descent step, the same update rule as Ep02, just applied layer by layer.
That backward pass is backpropagation, the algorithm that trains every neural network you have heard of.
How a network learns

A multi-layer perceptron (MLP) stacks an input layer, one or more hidden layers and an output layer, with every neuron connected to every neuron in the next layer. Training repeats the same loop:
- Forward pass: compute predictions.
- Loss: measure the error (log loss for classification, MSE for regression).
- Backpropagation: compute the gradient of the loss with respect to every weight.
- Update: nudge every weight downhill.
A few terms you’ll see in every deep learning tool:
- Epoch: one full pass over the training data.
- Batch size: how many examples are used for each update. Updating on small random batches is stochastic gradient descent (SGD).
- Learning rate: the step size, exactly as in Ep02.
- Optimizer: the update rule. Adam, which adapts the step size for each weight, is the usual default.
- Parameters: every weight and bias. A layer with n_in inputs and n_out neurons has (n_in + 1) × n_out of them.
Step 2: A neural network with scikit-learn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
mlp = make_pipeline(
StandardScaler(),
MLPClassifier(hidden_layer_sizes=(32, 16), activation="relu",
max_iter=1000, random_state=0),
)
mlp.fit(X_train, y_train)
net = mlp[-1]
print("layers (weight shapes):", [w.shape for w in net.coefs_])
print("parameters:", sum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_))
print("train accuracy:", round(mlp.score(X_train, y_train), 3))
print("test accuracy: ", round(mlp.score(X_test, y_test), 3))
Output:
layers (weight shapes): [(30, 32), (32, 16), (16, 1)]
parameters: 1537
train accuracy: 0.998
test accuracy: 0.956
What’s actually happening here
hidden_layer_sizes=(32, 16) builds two hidden layers of 32 and 16 ReLU neurons on top of the 30 input features. The parameter count checks out by hand: (30 + 1) × 32 + (32 + 1) × 16 + (16 + 1) × 1 = 992 + 528 + 17 = 1,537. Scaling matters even more than for KNN or SVMs, because unscaled inputs make gradient descent unstable.
Now look at the two scores. 99.8% on training data and 95.6% on the test set. The network has learned the training set almost perfectly and does noticeably worse on data it hasn’t seen. That gap is the most important thing in machine learning, and the rest of this post is about measuring and controlling it.
scikit-learn’s
MLPClassifieris perfect for learning and for small tabular problems. For images, text and anything large, you’ll use a deep learning framework such as PyTorch or TensorFlow/Keras, which run on GPUs and offer CNN, RNN and transformer layers. Module 4 covers those.
Overfitting and the bias–variance trade-off

Every model’s error on new data comes from two sources:
- Bias: error from wrong assumptions. A model that is too simple (a straight line for a curved pattern) misses the real signal. It does badly on training and test data. That is underfitting.
- Variance: error from sensitivity to the particular training sample. A model that is too flexible fits the noise too, so it looks brilliant on training data and disappoints on test data. That is overfitting.
Making a model more complex lowers bias but raises variance, so the goal is the sweet spot between them. You have seen this in every post: tree depth in Ep03, boosting rounds and C in Ep04, k in Ep05. Neural networks, with thousands or millions of parameters, sit at the flexible extreme and overfit very easily.
How to read the symptoms:
- Train error high, test error high → underfitting. Use a bigger model, add features, train longer, regularize less.
- Train error low, test error much higher → overfitting. Get more data, regularize, simplify, or stop training earlier.
- Training loss keeps falling while validation loss starts rising → overfitting has begun at that epoch. Stop there.
Step 3: Regularization tames overfitting
Regularization adds a penalty to the loss that discourages extreme weights. The most common is L2 (also called weight decay or Ridge): loss + λ·Σw², which keeps all weights small and the model smooth. L1 (Lasso), λ·Σ|w|, pushes some weights exactly to zero and so performs feature selection. In MLPClassifier, alpha is the L2 strength. Here is a large network on a small, noisy dataset:
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=400, noise=0.4, random_state=0) # noisy, overlapping classes
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=80, random_state=0)
for alpha in [0.0001, 0.1, 1.0, 10.0]: # alpha = L2 regularization strength
net = MLPClassifier(hidden_layer_sizes=(100, 100), alpha=alpha, solver="lbfgs",
max_iter=5000, random_state=0).fit(X_train, y_train)
print(f"alpha={alpha:<7} train = {net.score(X_train, y_train):.3f} "
f"test = {net.score(X_test, y_test):.3f}")
Output:
alpha=0.0001 train = 1.000 test = 0.803
alpha=0.1 train = 1.000 test = 0.822
alpha=1.0 train = 0.812 test = 0.878
alpha=10.0 train = 0.600 test = 0.475
What’s actually happening here
With almost no regularization, 10,000+ weights learn 80 noisy points perfectly (train 1.000) and test at 0.803: textbook overfitting. At alpha=1.0 training accuracy drops to 0.812, because the network is no longer allowed to chase every noisy point, and test accuracy rises to 0.878, the best of the four. Push it to 10 and the penalty swamps the data: the model underfits and does badly on both sets. Training accuracy going down while test accuracy goes up is regularization working exactly as intended.
The other standard defences against overfitting:
- Early stopping: hold back a validation set and stop training when its score stops improving (
early_stopping=TrueinMLPClassifier). - Dropout: in deep learning frameworks, randomly switch off a fraction of neurons in each training step so the network can’t rely on any one of them.
- More data, or data augmentation for images (Ep12).
- A smaller network: fewer layers or neurons.
Cross-validation: a fair exam

A single train/test split is one exam. You might get lucky (or unlucky) with which rows landed in the test set. k-fold cross-validation gives the model k exams instead:
- Split the data into k equal folds (usually 5 or 10).
- Train on k − 1 folds and test on the remaining one.
- Repeat k times so every fold is the test set once.
- Report the mean score and its spread (standard deviation).
That’s what cross_val_score(model, X, y, cv=5) has been doing since Ep03. For classification, scikit-learn automatically uses stratified folds, which keep the class ratio the same in each fold. Cross-validation is also how hyperparameters should be tuned (GridSearchCV in Ep04). The rule that holds it all together: the test set is touched once, at the very end.
The accuracy trap
Accuracy, the share of predictions that are correct, is the first metric everyone reaches for, and on imbalanced data it lies. Here are 2,000 transactions of which about 5% are fraud:
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import train_test_split
# 2,000 transactions, about 5% fraud (class 1)
X, y = make_classification(n_samples=2000, n_features=10, weights=[0.95, 0.05],
class_sep=0.8, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0)
models = {
"always 'not fraud'": DummyClassifier(strategy="most_frequent"),
"logistic": LogisticRegression(max_iter=1000),
"logistic (balanced)": LogisticRegression(max_iter=1000, class_weight="balanced"),
}
for name, model in models.items():
pred = model.fit(X_train, y_train).predict(X_test)
print(f"{name:<20} acc={accuracy_score(y_test, pred):.3f} "
f"precision={precision_score(y_test, pred, zero_division=0):.3f} "
f"recall={recall_score(y_test, pred):.3f} f1={f1_score(y_test, pred):.3f}")
Output:
always 'not fraud' acc=0.946 precision=0.000 recall=0.000 f1=0.000
logistic acc=0.960 precision=0.769 recall=0.370 f1=0.500
logistic (balanced) acc=0.878 precision=0.298 recall=0.926 f1=0.450
What’s actually happening here
A “model” that never predicts fraud scores 94.6% accuracy while catching zero frauds. Plain logistic regression looks better at 96% accuracy, but it catches only 37% of the fraud. With class_weight="balanced", mistakes on the rare class cost more during training: accuracy drops to 87.8%, yet the model now catches 92.6% of the fraud. For a bank, that third model is by far the most useful, and accuracy ranks it last. To see why, we need the confusion matrix.
The confusion matrix, precision, recall and F1

For a two-class problem, every prediction falls into one of four boxes:
- True positive (TP): predicted positive, really positive. A cancer, caught.
- False negative (FN): predicted negative, really positive. A cancer, missed.
- False positive (FP): predicted positive, really negative. A false alarm.
- True negative (TN): predicted negative, really negative. Correctly cleared.
Every metric is a ratio of these boxes:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
Precision = TP / (TP + FP) of everything flagged positive, how much really was?
Recall = TP / (TP + FN) of all real positives, how many did we catch?
F1-score = 2 · Precision · Recall / (Precision + Recall)
Specificity = TN / (TN + FP) of all real negatives, how many were cleared?
Precision is about trusting the alarms. Recall (also called sensitivity) is about not missing anything. F1 is their harmonic mean, which is only high when both are high, so it is the go-to single number for imbalanced problems.
Which one to optimise depends on which mistake costs more:
- Missing a positive is costly → maximise recall. Cancer screening, fraud detection, safety defects. A false alarm only costs a follow-up check.
- A false alarm is costly → maximise precision. Spam filters (an important email lost in the spam folder), recommending surgery, accusing a customer of fraud.
- Both matter, classes imbalanced → F1 (or the area under the precision–recall curve).
- Accuracy only when classes are roughly balanced and both errors cost about the same.
Step 4: Moving the threshold
Classifiers output a probability, and the default rule says “positive if ≥ 0.5”. That 0.5 is a choice, and moving it trades precision for recall. Here we make malignant the positive class, since that is the case we must not miss:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # make malignant = 1 (the class we must not miss)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=3)
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.05, max_iter=1000))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1] # P(malignant)
for threshold in (0.5, 0.2):
pred = (proba >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print(f"threshold {threshold}: TP={tp} FN={fn} FP={fp} TN={tn} "
f"precision={precision_score(y_test, pred):.3f} recall={recall_score(y_test, pred):.3f}")
Output:
threshold 0.5: TP=60 FN=4 FP=0 TN=107 precision=1.000 recall=0.938
threshold 0.2: TP=64 FN=0 FP=11 TN=96 precision=0.853 recall=1.000
What’s actually happening here
At the default 0.5 threshold the model never raises a false alarm (precision 1.000) but misses 4 malignant tumours. Lower the threshold to 0.2, so anything with even a 20% chance of being malignant gets flagged, and all 64 cancers are caught (recall 1.000), at the cost of 11 healthy patients sent for an extra check. For a screening tool that is clearly the better trade. Same model, same weights; only the decision rule changed. A model’s metrics describe the model plus its threshold, so always choose the threshold on purpose, using validation data, not the test set.
Module 2 in one list
That completes the supervised toolbox. All nine algorithms, and when each one is the first thing to try:
- Linear regression: numeric targets with roughly linear relationships; when you need to explain coefficients.
- Logistic regression: a fast, interpretable baseline for any classification problem.
- Decision tree: when the rules must be readable and auditable.
- Random forest: a strong, low-effort default for tabular data.
- Gradient boosting: maximum accuracy on tabular data, with tuning.
- SVM: small to medium, high-dimensional data with a clear margin.
- KNN: small datasets where similarity is meaningful; recommendations.
- Naive Bayes: text and very high-dimensional data; instant training.
- Neural network: large datasets and complex patterns; the gateway to deep learning.
Whichever you pick, the evaluation rules are the same: hold out a test set, tune with cross-validation, and choose the metric that matches the real cost of each mistake.
Common first-time mistakes
- Reporting accuracy on imbalanced data. Always look at the confusion matrix, recall and precision too.
- Tuning on the test set. Every look at the test set while making decisions leaks information. Use cross-validation or a separate validation set.
- Preprocessing before splitting. Fitting a scaler, PCA or oversampling (like SMOTE) on the full dataset leaks test information into training. Put preprocessing inside a
Pipeline. - Not scaling inputs for a neural network. Training becomes slow or unstable.
- Making the network bigger to fix overfitting. If test accuracy lags training accuracy, more capacity makes it worse. Regularize, add data or simplify.
- Trusting the default 0.5 threshold. Pick it based on the cost of each kind of error.
The honest limitations
Neural networks are data-hungry, slower to train than the other eight algorithms, sensitive to scaling, learning rate and initialization, and hard to explain: 1,537 weights tell you very little about why a tumour was flagged. On small tabular datasets they rarely beat a tuned random forest or gradient boosting model. Their strength appears with large datasets and unstructured inputs such as images, audio and text, which is exactly where Module 4 picks them back up.
Metrics have limits too. Every number here is an estimate from a sample of data, and a model that scores well today can degrade as real-world data drifts. We’ll come back to monitoring that in Module 6.
Where to go next
- scikit-learn: Neural network models (supervised), covering
MLPClassifier,MLPRegressor, regularization and practical tips. - scikit-learn: Metrics and scoring, covering every classification and regression metric, plus threshold tuning.
That wraps up supervised learning. Every model so far needed labels, the right answers, to learn from. In Ep07 we start Module 3: unsupervised learning, where there are no labels at all. We’ll begin with K-means, which groups data into k clusters by moving centroids, and hierarchical clustering, which builds a family tree of groups you can cut at any level.
This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Try training the XOR network with only 2 hidden neurons, or move the fraud model’s threshold, and tell me what happened to recall.

Comments (...)
You must be signed in to join the discussion.