Overfitting and Regularization
Ridge, L2-penalised logistic regression, and a PyTorch MLP
Three demonstrations of the same idea in three different APIs — which is exactly what makes it a good exam question.
Part 1 — Ridge on diabetes regression
Data and split
diab_sk = datasets.load_diabetes()
X, y = diab_sk['data'], diab_sk['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=999)
# (309, 10), (133, 10)
Two models, side by side
LR = linear_model.LinearRegression()
LR.fit(X_train, y_train); y_pred = LR.predict(X_test)
LRr = linear_model.Ridge(alpha=.05)
LRr.fit(X_train, y_train); y_predr = LRr.predict(X_test)
The only difference is the estimator class and alpha. The fit/predict calls are identical — that is the scikit-learn contract, and it is why swapping models never requires rewriting the pipeline.
Results
print('MSE score: ', mean_squared_error(y_test, y_pred), mean_squared_error(y_test, y_predr))
# 2537.215 2507.740
print('R2 score: ', r2_score(y_test, y_pred), r2_score(y_test, y_predr))
# 0.52358 0.52911
| Model | MSE | $R^2$ |
|---|---|---|
| OLS | 2537.22 | 0.5236 |
| Ridge $\alpha=0.05$ | 2507.74 | 0.5291 |
The improvement is 1.2% on MSE. Explain why it is small: with $N=309$ and $d=10$, the model is not badly overparameterised, so there is not much variance to remove. Regularisation helps in proportion to the overfitting it prevents.
plt.plot(y_test[:10], '*', label='actual')
plt.plot(y_pred[:10], 'o', label='pred')
plt.plot(y_predr[:10], '+', label='predR')
Ten samples, three series — a quick visual check that ridge's predictions are shrunken toward the mean relative to OLS. That shrinkage is what "L2 penalty" looks like in prediction space.
alpha in scikit-learn's Ridge is the $\lambda$ in $\lambda\sum w_i^2$ — it is not a learning rate. Confusing the two names is a common slip.
Part 2 — L2-penalised logistic regression under scarcity
A deliberately brutal split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.9)
# (15, 4), (135, 4)
15 training samples for 4 features and 3 classes. This is engineered to make regularisation visible.
Two settings
LR_class = linear_model.LogisticRegression() # default C=1
LR_class.fit(X_train, y_train); y_pred = LR_class.predict(X_test)
LR_class = linear_model.LogisticRegression(C=10, penalty='l2') # weaker regularisation
LR_class.fit(X_train, y_train); y_predR = LR_class.predict(X_test)
Results
print('Classification accuracy: ', 100*accuracy_score(y_pred,y_test), 100*accuracy_score(y_predR,y_test))
# 95.5556 97.7778
| Model | Test accuracy |
|---|---|
default C=1, l2 | 95.56% |
C=10, l2 | 97.78% |
Bigger C = less regularisation. Here the larger C wins, because at 15 samples the default $C=1$ is over-regularising — it shrinks the coefficients so hard that the model cannot use the features it has. If you write "C=10 means more regularisation" you have the direction backwards. Same variable letter as SVM's $C$, same meaning: it is the inverse of the penalty strength.
Also note penalty='l2' is the default anyway — writing it explicitly is a documentation gesture, not a change.
Part 3 — the PyTorch MLP
Convert to tensors
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.float32).reshape(-1, 1)
reshape(-1,1) because MSELoss compares tensors elementwise and a (309,) target against a (309,1) prediction broadcasts wrongly.
DataLoader
trainloader = DataLoader(list(zip(X_train, y_train)), batch_size=8, shuffle=True)
testloader = DataLoader(list(zip(X_test, y_test)), batch_size=8, shuffle=False)
zip pairs each input with its target; batch_size=8 means 39 iterations per epoch on 309 samples. shuffle=True for training, False for testing — shuffling the test set changes nothing numerically but makes the printed predictions unreadable.
The model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.fc2 = nn.Linear(20, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
Two linear layers, one ReLU, no output activation — because the target is a continuous score, not a probability. Adding a sigmoid here would clamp the output to (0,1) and destroy the model.
print(net)
# Net(fc1: Linear(10,20), fc2: Linear(20,1))
Parameter count: $(10\times20+20)+(20\times1+1) = 220+21 = \mathbf{241}$.
Training loop
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.01, weight_decay=1e-2)
for epoch in range(100):
running_loss = 0.0
for i, data in enumerate(trainloader):
inputs, labels = data
optimizer.zero_grad() # 1. clear old gradients
outputs = net(inputs) # 2. forward
loss = criterion(outputs, labels)
loss.backward() # 3. backward
optimizer.step() # 4. update
running_loss += loss.item()
The four-line core is the whole of deep learning, and it maps exactly onto the backpropagation slide in W8L3: zero the gradients, forward pass, backward pass, update. zero_grad() is there because PyTorch accumulates gradients by default — omit it and you sum gradients across batches.
weight_decay is L2
> weight_decay=1e-2 adds $\lambda\|w\|^2$ to the loss inside the optimiser. That is the same regularisation as Ridge(alpha=...), expressed through the optimiser instead of the estimator. This is the connection that makes the three parts of the notebook one idea.
Results
print('MSE score: ', mean_squared_error(y_test, y_pred)) # 2473.15
print('R2 score: ', r2_score(y_test, y_pred)) # 0.5356
| Model | MSE | $R^2$ |
|---|---|---|
| OLS | 2537.22 | 0.5236 |
| Ridge | 2507.74 | 0.5291 |
| MLP (241 params) | 2473.15 | 0.5356 |
The MLP is best, but only marginally — 2.5% better than OLS with 241 parameters instead of 11. That is the honest reading: the relationship is close to linear, so the extra capacity buys little, and the improvement is within the noise of a single 133-sample test split.
The unifying table
| Part | API | Regularisation expressed as | Effect |
|---|---|---|---|
| 1 | Ridge(alpha=0.05) | explicit $\lambda\sum w^2$ | MSE 2537 → 2508 |
| 2 | LogisticRegression(C=10) | inverse penalty | acc 95.6% → 97.8% |
| 3 | Adam(weight_decay=1e-2) | implicit L2 in the optimiser | MSE 2473 |
"Explain how this notebook demonstrates regularisation." It shows the same penalty applied through three interfaces: alpha in Ridge, C (inverted) in logistic regression, and weight_decay in the optimiser. In each case the training fit is slightly worse and the test fit is slightly better — which is the definition of regularisation working. The magnitude of the benefit tracks how much the unregularised model was overfitting: small on 309×10, large on 15×4.


