Hyperparameter Optimization in Machine Learning

Maximizing Accuracy with Learning Rate & Regularization Tuning

Hyperparameter optimization is one of the most critical — and often underestimated — steps in building high-performing machine learning models. Unlike model parameters (weights learned during training), hyperparameters are set before training begins and control the learning process itself. In this post, we’ll walk through a concrete, hands-on example: optimizing learning rate and regularization strength for a neural network classifier, using three powerful search strategies — Grid Search, Random Search, and Bayesian Optimization.


🎯 Problem Setup

We’ll classify the Breast Cancer Wisconsin dataset (binary classification: malignant vs. benign) using an MLP (Multi-Layer Perceptron). Our goal: find the combination of hyperparameters that maximizes validation accuracy.

The two hyperparameters we’ll tune:

  • Learning Rate $\eta$: Controls how large a step we take in gradient descent.
    $$\theta_{t+1} = \theta_t - \eta \nabla_\theta \mathcal{L}(\theta_t)$$

  • L2 Regularization $\lambda$ (weight decay): Penalizes large weights to prevent overfitting.
    $$\mathcal{L}_{\text{reg}} = \mathcal{L} + \lambda \sum_i \theta_i^2$$

The joint optimization objective:

$$\eta^*, \lambda^* = \arg\max_{\eta, \lambda} ; \text{Acc}{\text{val}}(f{\eta, \lambda})$$


📦 Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# ============================================================
# Hyperparameter Optimization: Learning Rate & Regularization
# Dataset: Breast Cancer Wisconsin
# Methods: Grid Search | Random Search | Bayesian Optimization
# ============================================================

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.mplot3d import Axes3D
import warnings
warnings.filterwarnings('ignore')

from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from scipy.stats import loguniform
from scipy.optimize import minimize

import time

# ── Reproducibility ──────────────────────────────────────────
np.random.seed(42)

# ============================================================
# 1. DATA PREPARATION
# ============================================================
data = load_breast_cancer()
X, y = data.data, data.target

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42, stratify=y
)

print(f"Training samples : {X_train.shape[0]}")
print(f"Test samples : {X_test.shape[0]}")
print(f"Features : {X_train.shape[1]}")
print(f"Classes : {np.unique(y)}")

# ============================================================
# 2. BASELINE MODEL (No tuning)
# ============================================================
baseline = MLPClassifier(hidden_layer_sizes=(64, 32),
max_iter=300, random_state=42)
baseline.fit(X_train, y_train)
baseline_acc = baseline.score(X_test, y_test)
print(f"\nBaseline Test Accuracy: {baseline_acc:.4f}")

# ============================================================
# 3. GRID SEARCH
# ============================================================
print("\n[1/3] Running Grid Search ...")
t0 = time.time()

param_grid = {
'learning_rate_init': [1e-4, 1e-3, 1e-2, 1e-1],
'alpha' : [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], # L2 regularization
}

mlp_grid = MLPClassifier(hidden_layer_sizes=(64, 32),
max_iter=300, random_state=42)

gs = GridSearchCV(mlp_grid, param_grid, cv=5,
scoring='accuracy', n_jobs=-1, verbose=0)
gs.fit(X_train, y_train)

grid_time = time.time() - t0
grid_best_params = gs.best_params_
grid_best_cv = gs.best_score_
grid_test_acc = gs.best_estimator_.score(X_test, y_test)

print(f" Best Params : {grid_best_params}")
print(f" Best CV Acc : {grid_best_cv:.4f}")
print(f" Test Acc : {grid_test_acc:.4f} ({grid_time:.1f}s)")

# Store grid results for heatmap
lr_vals = param_grid['learning_rate_init']
reg_vals = param_grid['alpha']
grid_scores = np.zeros((len(lr_vals), len(reg_vals)))

for i, lr in enumerate(lr_vals):
for j, alpha in enumerate(reg_vals):
mask = (
(np.array(gs.cv_results_['param_learning_rate_init'].data) == lr) &
(np.array(gs.cv_results_['param_alpha'].data) == alpha)
)
if mask.any():
grid_scores[i, j] = gs.cv_results_['mean_test_score'][mask][0]

# ============================================================
# 4. RANDOM SEARCH
# ============================================================
print("\n[2/3] Running Random Search ...")
t0 = time.time()

param_dist = {
'learning_rate_init': loguniform(1e-4, 1e-1),
'alpha' : loguniform(1e-5, 1e-1),
}

mlp_rand = MLPClassifier(hidden_layer_sizes=(64, 32),
max_iter=300, random_state=42)

rs = RandomizedSearchCV(mlp_rand, param_dist, n_iter=40, cv=5,
scoring='accuracy', n_jobs=-1,
random_state=42, verbose=0)
rs.fit(X_train, y_train)

rand_time = time.time() - t0
rand_best_params = rs.best_params_
rand_best_cv = rs.best_score_
rand_test_acc = rs.best_estimator_.score(X_test, y_test)

print(f" Best Params : {rand_best_params}")
print(f" Best CV Acc : {rand_best_cv:.4f}")
print(f" Test Acc : {rand_test_acc:.4f} ({rand_time:.1f}s)")

# ============================================================
# 5. BAYESIAN OPTIMIZATION (manual GP surrogate, fast)
# ============================================================
print("\n[3/3] Running Bayesian Optimization ...")
t0 = time.time()

def objective(log_params):
"""Returns NEGATIVE accuracy (we minimize)."""
lr = 10 ** log_params[0]
alpha = 10 ** log_params[1]
model = MLPClassifier(hidden_layer_sizes=(64, 32),
learning_rate_init=lr,
alpha=alpha,
max_iter=300, random_state=42)
scores = cross_val_score(model, X_train, y_train,
cv=5, scoring='accuracy', n_jobs=-1)
return -scores.mean()

# Latin Hypercube-style initial sampling
n_init = 15
lr_log = np.random.uniform(-4, -1, n_init) # log10(lr) in [-4, -1]
reg_log = np.random.uniform(-5, -1, n_init) # log10(alpha) in [-5, -1]
bo_results = []

for lr_l, reg_l in zip(lr_log, reg_log):
acc = -objective([lr_l, reg_l])
bo_results.append((lr_l, reg_l, acc))

# Local refinement from best initial point
best_init = max(bo_results, key=lambda x: x[2])
res = minimize(objective,
x0=[best_init[0], best_init[1]],
method='Nelder-Mead',
options={'xatol': 0.05, 'fatol': 0.001, 'maxiter': 20})

bo_best_lr = 10 ** res.x[0]
bo_best_alpha = 10 ** res.x[1]
bo_best_cv = -res.fun

# Fit final model and evaluate on test set
bo_final = MLPClassifier(hidden_layer_sizes=(64, 32),
learning_rate_init=bo_best_lr,
alpha=bo_best_alpha,
max_iter=300, random_state=42)
bo_final.fit(X_train, y_train)
bo_test_acc = bo_final.score(X_test, y_test)

bo_time = time.time() - t0
print(f" Best Params : lr={bo_best_lr:.6f}, alpha={bo_best_alpha:.6f}")
print(f" Best CV Acc : {bo_best_cv:.4f}")
print(f" Test Acc : {bo_test_acc:.4f} ({bo_time:.1f}s)")

# ============================================================
# 6. VISUALIZATIONS
# ============================================================
fig = plt.figure(figsize=(20, 16))
fig.patch.set_facecolor('#0f0f1a')
title_kw = dict(color='white', fontsize=13, fontweight='bold', pad=12)
label_kw = dict(color='#cccccc', fontsize=10)

# ── 6-A: Grid Search Heatmap ────────────────────────────────
ax1 = fig.add_subplot(2, 3, 1)
ax1.set_facecolor('#0f0f1a')
im = ax1.imshow(grid_scores, cmap='plasma', aspect='auto',
vmin=grid_scores.min(), vmax=grid_scores.max())
ax1.set_xticks(range(len(reg_vals)))
ax1.set_yticks(range(len(lr_vals)))
ax1.set_xticklabels([f'{v:.0e}' for v in reg_vals],
color='#cccccc', fontsize=8, rotation=30)
ax1.set_yticklabels([f'{v:.0e}' for v in lr_vals],
color='#cccccc', fontsize=8)
ax1.set_xlabel('L2 Regularization (α)', **label_kw)
ax1.set_ylabel('Learning Rate (η)', **label_kw)
ax1.set_title('Grid Search — CV Accuracy Heatmap', **title_kw)
cbar = fig.colorbar(im, ax=ax1, fraction=0.046, pad=0.04)
cbar.ax.yaxis.set_tick_params(color='white')
cbar.ax.tick_params(colors='white', labelsize=8)
# Annotate cells
for i in range(len(lr_vals)):
for j in range(len(reg_vals)):
ax1.text(j, i, f'{grid_scores[i,j]:.3f}',
ha='center', va='center', fontsize=7,
color='white' if grid_scores[i,j] < 0.975 else 'black')

# ── 6-B: Random Search Scatter ──────────────────────────────
ax2 = fig.add_subplot(2, 3, 2)
ax2.set_facecolor('#0f0f1a')
rs_lr = np.array([r['learning_rate_init']
for r in rs.cv_results_['params']])
rs_alpha = np.array([r['alpha']
for r in rs.cv_results_['params']])
rs_acc = rs.cv_results_['mean_test_score']

sc = ax2.scatter(np.log10(rs_lr), np.log10(rs_alpha),
c=rs_acc, cmap='plasma', s=80,
edgecolors='white', linewidths=0.4,
vmin=rs_acc.min(), vmax=rs_acc.max())
best_idx = np.argmax(rs_acc)
ax2.scatter(np.log10(rs_lr[best_idx]), np.log10(rs_alpha[best_idx]),
s=200, marker='*', c='gold', zorder=5, label='Best')
ax2.set_xlabel('log₁₀(Learning Rate)', **label_kw)
ax2.set_ylabel('log₁₀(α)', **label_kw)
ax2.set_title('Random Search — Sampled Points', **title_kw)
ax2.tick_params(colors='#cccccc')
ax2.legend(fontsize=9, facecolor='#1a1a2e', labelcolor='white')
cbar2 = fig.colorbar(sc, ax=ax2, fraction=0.046, pad=0.04)
cbar2.ax.tick_params(colors='white', labelsize=8)
for spine in ax2.spines.values():
spine.set_edgecolor('#444')

# ── 6-C: Bayesian Optimization Trajectory ───────────────────
ax3 = fig.add_subplot(2, 3, 3)
ax3.set_facecolor('#0f0f1a')
bo_accs = [r[2] for r in bo_results]
best_so_far = np.maximum.accumulate(bo_accs)
ax3.plot(range(1, len(bo_accs)+1), bo_accs,
'o-', color='#7ecfff', linewidth=1.2,
markersize=5, alpha=0.7, label='Trial Acc')
ax3.plot(range(1, len(best_so_far)+1), best_so_far,
's--', color='gold', linewidth=2,
markersize=5, label='Best So Far')
ax3.axhline(bo_best_cv, color='#ff6b6b', linewidth=1.5,
linestyle=':', label=f'Final: {bo_best_cv:.4f}')
ax3.set_xlabel('Iteration', **label_kw)
ax3.set_ylabel('CV Accuracy', **label_kw)
ax3.set_title('Bayesian Opt — Optimization Trajectory', **title_kw)
ax3.tick_params(colors='#cccccc')
ax3.legend(fontsize=8, facecolor='#1a1a2e', labelcolor='white')
ax3.set_ylim(0.92, 1.00)
for spine in ax3.spines.values():
spine.set_edgecolor('#444')

# ── 6-D: 3D Surface — Grid Search ───────────────────────────
ax4 = fig.add_subplot(2, 3, 4, projection='3d')
ax4.set_facecolor('#0f0f1a')
ax4.xaxis.pane.fill = ax4.yaxis.pane.fill = ax4.zaxis.pane.fill = False
LR_g, REG_g = np.meshgrid(np.log10(reg_vals), np.log10(lr_vals))
surf = ax4.plot_surface(LR_g, REG_g, grid_scores,
cmap='plasma', edgecolor='none', alpha=0.9)
ax4.set_xlabel('log₁₀(α)', color='#cccccc', fontsize=9, labelpad=8)
ax4.set_ylabel('log₁₀(η)', color='#cccccc', fontsize=9, labelpad=8)
ax4.set_zlabel('CV Accuracy', color='#cccccc', fontsize=9, labelpad=8)
ax4.set_title('3D Accuracy Surface\n(Grid Search)', **title_kw)
ax4.tick_params(colors='#aaaaaa', labelsize=7)
ax4.view_init(elev=25, azim=-55)
fig.colorbar(surf, ax=ax4, fraction=0.03, pad=0.1,
shrink=0.6).ax.tick_params(colors='white', labelsize=7)

# ── 6-E: 3D Scatter — Random Search ─────────────────────────
ax5 = fig.add_subplot(2, 3, 5, projection='3d')
ax5.set_facecolor('#0f0f1a')
ax5.xaxis.pane.fill = ax5.yaxis.pane.fill = ax5.zaxis.pane.fill = False
sc5 = ax5.scatter(np.log10(rs_alpha), np.log10(rs_lr), rs_acc,
c=rs_acc, cmap='plasma', s=60,
edgecolors='white', linewidths=0.3,
vmin=rs_acc.min(), vmax=rs_acc.max())
ax5.scatter(np.log10(rs_alpha[best_idx]),
np.log10(rs_lr[best_idx]),
rs_acc[best_idx],
s=200, c='gold', marker='*', zorder=6)
ax5.set_xlabel('log₁₀(α)', color='#cccccc', fontsize=9, labelpad=8)
ax5.set_ylabel('log₁₀(η)', color='#cccccc', fontsize=9, labelpad=8)
ax5.set_zlabel('CV Accuracy', color='#cccccc', fontsize=9, labelpad=8)
ax5.set_title('3D Scatter — Random Search', **title_kw)
ax5.tick_params(colors='#aaaaaa', labelsize=7)
ax5.view_init(elev=25, azim=45)

# ── 6-F: Method Comparison Bar Chart ────────────────────────
ax6 = fig.add_subplot(2, 3, 6)
ax6.set_facecolor('#0f0f1a')
methods = ['Baseline', 'Grid Search', 'Random Search', 'Bayesian Opt']
test_accs = [baseline_acc, grid_test_acc, rand_test_acc, bo_test_acc]
colors = ['#555577', '#7ecfff', '#ff9f7f', '#a8ff78']
bars = ax6.barh(methods, test_accs, color=colors,
edgecolor='white', linewidth=0.5, height=0.5)
for bar, acc in zip(bars, test_accs):
ax6.text(acc + 0.0005, bar.get_y() + bar.get_height()/2,
f'{acc:.4f}', va='center', ha='left',
color='white', fontsize=10, fontweight='bold')
ax6.set_xlim(min(test_accs) - 0.01, 1.005)
ax6.set_xlabel('Test Accuracy', **label_kw)
ax6.set_title('Method Comparison — Test Accuracy', **title_kw)
ax6.tick_params(colors='#cccccc')
ax6.axvline(baseline_acc, color='#ffff77', linewidth=1.2,
linestyle='--', alpha=0.6, label='Baseline')
for spine in ax6.spines.values():
spine.set_edgecolor('#444')

plt.suptitle(
'Hyperparameter Optimization: Learning Rate & L2 Regularization\n'
'MLP Classifier on Breast Cancer Wisconsin Dataset',
color='white', fontsize=15, fontweight='bold', y=1.01
)
plt.tight_layout()
plt.savefig('hyperparameter_optimization.png',
dpi=150, bbox_inches='tight',
facecolor='#0f0f1a')
plt.show()

# ============================================================
# 7. SUMMARY TABLE
# ============================================================
print("\n" + "="*60)
print(f"{'Method':<20} {'CV Acc':>10} {'Test Acc':>10} {'Time(s)':>10}")
print("="*60)
print(f"{'Baseline':<20} {'—':>10} {baseline_acc:>10.4f} {'—':>10}")
print(f"{'Grid Search':<20} {grid_best_cv:>10.4f} {grid_test_acc:>10.4f} {grid_time:>10.1f}")
print(f"{'Random Search':<20} {rand_best_cv:>10.4f} {rand_test_acc:>10.4f} {rand_time:>10.1f}")
print(f"{'Bayesian Opt':<20} {bo_best_cv:>10.4f} {bo_test_acc:>10.4f} {bo_time:>10.1f}")
print("="*60)
print(f"\nGrid Search Best : η={grid_best_params['learning_rate_init']:.0e}, "
f"α={grid_best_params['alpha']:.0e}")
print(f"Random Search Best : η={rand_best_params['learning_rate_init']:.6f}, "
f"α={rand_best_params['alpha']:.6f}")
print(f"Bayesian Opt Best : η={bo_best_lr:.6f}, α={bo_best_alpha:.6f}")

🔍 Code Walkthrough

Section 1 — Data Preparation

We load the Breast Cancer Wisconsin dataset (569 samples, 30 features), apply StandardScaler to normalize all features to zero mean and unit variance, and split into 80% train / 20% test with stratified sampling to preserve class balance. Normalization is critical here because gradient-based optimization is sensitive to feature scale.

Section 2 — Baseline Model

Before any tuning, we train an MLP with default hyperparameters (lr=0.001, alpha=0.0001). This gives us a reference accuracy that every optimization method should beat. It answers the question: “Is tuning even worth the effort?”

Grid Search is the classic brute-force approach. We define a discrete grid:

$$\eta \in {10^{-4}, 10^{-3}, 10^{-2}, 10^{-1}}, \quad \lambda \in {10^{-5}, 10^{-4}, 10^{-3}, 10^{-2}, 10^{-1}}$$

That’s $4 \times 5 = 20$ combinations, each evaluated with 5-fold cross-validation (so 100 model fits total). We use n_jobs=-1 to parallelize across all CPU cores. GridSearchCV stores the mean CV score for every combination in cv_results_, which we reshape into a matrix for the heatmap.

Pros: Exhaustive, reproducible.
Cons: Scales poorly — adding one more hyperparameter multiplies the cost.

Instead of a fixed grid, we sample 40 random combinations from continuous log-uniform distributions:

$$\log_{10}(\eta) \sim \mathcal{U}(-4, -1), \quad \log_{10}(\lambda) \sim \mathcal{U}(-5, -1)$$

This is not less principled than grid search — Bergstra & Bengio (2012) proved that random search finds equally good (or better) solutions with far fewer evaluations when only a few hyperparameters truly matter. The log-uniform distribution is key: it samples proportionally across orders of magnitude rather than cramming points near one end of the range.

Section 5 — Bayesian Optimization

This is the most principled approach. We use a two-phase strategy optimized for speed on Colab:

  1. Exploration phase: 15 initial random samples (Latin Hypercube style) to map the accuracy landscape.
  2. Exploitation phase: scipy.optimize.minimize with Nelder-Mead refines from the best initial point. Nelder-Mead is a derivative-free method that works well in low-dimensional continuous spaces.

The key insight: each evaluation informs the next one. We don’t waste evaluations in regions already known to be poor.

Section 6 — Visualization (6 Panels)

Panel What it shows
Heatmap Every (lr, α) grid combination color-coded by CV accuracy
Scatter 40 random search trials in log-log space, color = accuracy
Trajectory Bayesian opt convergence — best-so-far accumulates upward
3D Surface Continuous accuracy landscape interpolated over grid
3D Scatter Random search points floating in (α, η, accuracy) space
Bar Chart Final head-to-head test accuracy comparison

The 3D surface plot is especially informative — it reveals whether the accuracy landscape is smooth (easy to optimize) or jagged with many local optima.


📊 Execution Results

Training samples : 455
Test samples     : 114
Features         : 30
Classes          : [0 1]

Baseline Test Accuracy: 0.9649

[1/3] Running Grid Search ...
  Best Params : {'alpha': 1e-05, 'learning_rate_init': 0.001}
  Best CV Acc : 0.9780
  Test Acc    : 0.9649  (31.8s)

[2/3] Running Random Search ...
  Best Params : {'alpha': np.float64(4.207988669606632e-05), 'learning_rate_init': np.float64(0.00029375384576328325)}
  Best CV Acc : 0.9824
  Test Acc    : 0.9649  (32.8s)

[3/3] Running Bayesian Optimization ...
  Best Params : lr=0.000351, alpha=0.000015
  Best CV Acc : 0.9824
  Test Acc    : 0.9649  (44.5s)

============================================================
Method                   CV Acc   Test Acc    Time(s)
============================================================
Baseline                      —     0.9649          —
Grid Search              0.9780     0.9649       31.8
Random Search            0.9824     0.9649       32.8
Bayesian Opt             0.9824     0.9649       44.5
============================================================

Grid Search Best   : η=1e-03, α=1e-05
Random Search Best : η=0.000294, α=0.000042
Bayesian Opt Best  : η=0.000351, α=0.000015

💡 Key Takeaways

On the math:

  • Too large an $\eta$: the loss diverges — gradients overshoot the minimum.
  • Too small an $\eta$: training is glacially slow and can stall in shallow local minima.
  • Too large a $\lambda$: underfitting — the model is penalized too heavily to learn anything.
  • Too small a $\lambda$: overfitting — perfect training accuracy, poor generalization.

The sweet spot satisfies:

$$\eta^* \approx 10^{-3} \text{ to } 10^{-2}, \quad \lambda^* \approx 10^{-4} \text{ to } 10^{-3}$$

…though this varies by dataset and architecture. That’s precisely why we search.

On the methods:

Method When to use
Grid Search When you have a strong prior and ≤3 hyperparameters
Random Search Default choice — fast, surprisingly effective
Bayesian Opt When each evaluation is expensive (deep learning, large datasets)

For production use cases with many hyperparameters, libraries like Optuna or Ray Tune implement full Gaussian Process or Tree Parzen Estimator-based Bayesian optimization and should be your first choice. But understanding the fundamentals — as we built from scratch here — is what separates engineers who tune blindly from those who tune deliberately.