Training from Scratch: the Seven-Step Workflow
Training from scratch means every parameter starts from random numbers and everything the model knows comes from your labelled data. It is the baseline the other nine strategies are measured against, and it is still the right choice more often than the hype suggests: for tabular data, for small models, for data unlike anything a public model was trained on (sensor signals, a new kind of microscope, your company's log format), and whenever licences or privacy rule out someone else's weights.
The workflow
- Problem and metric. What is predicted, for which decision, and which number tells you the model is good enough (accuracy, F1 of the rare class, mean absolute error in euros). Write down a baseline, such as the majority class or last week's value.
- Data and splits. Collect, clean and split into training, validation and test sets before looking closely, with the split that matches deployment (random, grouped by user, or by time; split strategies).
- Preprocessing fitted on the training set only: scalers, encoders, vocabularies (leakage rules).
- Architecture and initialisation. Start small. Initialise weights at random with a scale that keeps activations from exploding or vanishing, for example Xavier/Glorot for tanh layers and He for ReLU layers. Biases start at 0.
- Loss, optimiser and the training loop: forward pass, loss, gradients, update, repeated over mini-batches and epochs.
- Validate, tune and stop early. Track the validation metric every epoch, keep the best weights, tune the learning rate, width and regularisation on the validation set.
- Test once and save. Evaluate the chosen model on the untouched test set, then save the weights and the preprocessing, the seed and the versions.
The math of a small MLP
For a two-layer network with hidden units, input and classes:
Backpropagation gives the gradient of with respect to the logits as , and the chain rule carries it back through and the , whose derivative is (backpropagation for an MLP derives this, and initialisation the variance scales). Gradient descent then updates every weight by .
From scratch in NumPy
The seven steps on the two-moons problem, a 2-D data set no straight line separates. Validation decides when to stop; the test set is used once at the end.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
# 1. problem: classify points into two moons; metric: accuracy (classes are balanced)
# 2. data and splits: 60 % train, 20 % validation, 20 % test
X, y = make_moons(n_samples=500, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=0.4, random_state=0, stratify=y)
X_va, X_te, y_va, y_te = train_test_split(X_tmp, y_tmp, test_size=0.5, random_state=0, stratify=y_tmp)
# 3. preprocessing: standardise with training statistics only
mu, sd = X_tr.mean(0), X_tr.std(0)
X_tr, X_va, X_te = (X_tr - mu) / sd, (X_va - mu) / sd, (X_te - mu) / sd
# 4. architecture 2 -> 16 tanh -> 2 softmax, Xavier initialisation
rng = np.random.default_rng(0)
H = 16
W1 = rng.normal(0, np.sqrt(1 / 2), (2, H)); b1 = np.zeros(H)
W2 = rng.normal(0, np.sqrt(1 / H), (H, 2)); b2 = np.zeros(2)
def forward(X):
h = np.tanh(X @ W1 + b1)
z = h @ W2 + b2
e = np.exp(z - z.max(1, keepdims=True))
return h, e / e.sum(1, keepdims=True)
def loss_acc(X, y):
_, p = forward(X)
return -np.log(p[np.arange(len(y)), y]).mean(), (p.argmax(1) == y).mean()
# 5. train with full-batch gradient descent; 6. keep the best validation epoch
lr, best = 0.5, (np.inf, 0, None)
for epoch in range(1, 1501):
h, p = forward(X_tr)
g = p.copy(); g[np.arange(len(y_tr)), y_tr] -= 1; g /= len(y_tr) # dL/dz
gW2, gb2 = h.T @ g, g.sum(0)
gh = g @ W2.T * (1 - h ** 2) # back through tanh
gW1, gb1 = X_tr.T @ gh, gh.sum(0)
W1 -= lr * gW1; b1 -= lr * gb1; W2 -= lr * gW2; b2 -= lr * gb2
va_loss, va_acc = loss_acc(X_va, y_va)
if va_loss < best[0]:
best = (va_loss, epoch, [W1.copy(), b1.copy(), W2.copy(), b2.copy()])
if epoch in (1, 10, 100, 500, 1500):
tr_loss, tr_acc = loss_acc(X_tr, y_tr)
print(f"epoch {epoch:4d} train loss {tr_loss:.3f} acc {tr_acc:.3f} | val loss {va_loss:.3f} acc {va_acc:.3f}")
W1, b1, W2, b2 = best[2]
print("best validation epoch:", best[1])
# 7. test once
print(f"test accuracy: {loss_acc(X_te, y_te)[1]:.3f} on {len(y_te)} points")epoch 1 train loss 0.423 acc 0.823 | val loss 0.406 acc 0.870
epoch 10 train loss 0.352 acc 0.853 | val loss 0.319 acc 0.870
epoch 100 train loss 0.262 acc 0.897 | val loss 0.228 acc 0.910
epoch 500 train loss 0.187 acc 0.923 | val loss 0.149 acc 0.950
epoch 1500 train loss 0.168 acc 0.937 | val loss 0.146 acc 0.950
best validation epoch: 914
test accuracy: 0.970 on 100 points
The training loss keeps falling to the end, but the validation loss stops improving: its minimum is at epoch 914, and the loop restores those weights before the single test, which gives 0.970 on 100 points. With only 100 test points one mistake is a whole percentage point, so read 0.970 as "about 0.95 to 0.99", not as a precise number.
The same with scikit-learn
MLPClassifier does steps 4 to 6 for you: initialisation, Adam, mini-batches and early stopping on a validation fraction it carves out of the training data.
from sklearn.datasets import make_moons
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 = make_moons(n_samples=500, noise=0.25, random_state=0)
X_trva, X_te, y_trva, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
model = make_pipeline(
StandardScaler(),
MLPClassifier(hidden_layer_sizes=(16,), activation="tanh", learning_rate_init=0.01,
early_stopping=True, validation_fraction=0.25, n_iter_no_change=100,
max_iter=2000, random_state=0),
)
model.fit(X_trva, y_trva)
mlp = model[-1]
print("epochs run:", mlp.n_iter_, "| best validation accuracy:", round(mlp.best_validation_score_, 3))
print("parameters:", sum(w.size for w in mlp.coefs_) + sum(b.size for b in mlp.intercepts_))
print(f"test accuracy: {model.score(X_te, y_te):.3f}")epochs run: 322 | best validation accuracy: 0.91
parameters: 65
test accuracy: 0.910
scikit-learn picks its own validation quarter of the 400 non-test points and stops once the validation accuracy has not improved for 100 epochs, then keeps the best weights. It reports 65 parameters, not 82, because for two classes it uses a single sigmoid output instead of two softmax outputs: . Its test set is a different 100 points from the NumPy split, so the two test scores cannot be compared directly.
The same in PyTorch
Deep-learning frameworks make the loop explicit, which is what you want once you need custom losses, schedules, mixed precision or several devices. This is the template every recorded example of the course follows: seed, data, model, loss, optimiser, loop, validation with best-weight restore, a single test.
import copy
import numpy as np
import torch
from torch import nn
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
X, y = make_moons(n_samples=500, noise=0.25, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=0.4, random_state=0, stratify=y)
X_va, X_te, y_va, y_te = train_test_split(X_tmp, y_tmp, test_size=0.5, random_state=0, stratify=y_tmp)
mu, sd = X_tr.mean(0), X_tr.std(0)
t = lambda a: torch.tensor((a - mu) / sd, dtype=torch.float32)
X_tr, X_va, X_te = t(X_tr), t(X_va), t(X_te)
y_tr, y_va, y_te = map(torch.tensor, (y_tr, y_va, y_te))
model = nn.Sequential(nn.Linear(2, 16), nn.Tanh(), nn.Linear(16, 2)) # PyTorch's default init
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
best_loss, best_state, patience, wait = float("inf"), None, 20, 0
for epoch in range(1, 501):
model.train()
for idx in torch.randperm(len(y_tr)).split(32): # mini-batches of 32
loss = loss_fn(model(X_tr[idx]), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(X_va), y_va).item()
if val_loss < best_loss - 1e-4:
best_loss, best_state, wait = val_loss, copy.deepcopy(model.state_dict()), 0
else:
wait += 1
if wait == patience:
print(f"early stop at epoch {epoch}, best validation loss {best_loss:.3f}")
break
model.load_state_dict(best_state)
with torch.no_grad():
acc = (model(X_te).argmax(1) == y_te).float().mean().item()
print(f"test accuracy: {acc:.3f}")
print("trainable parameters:", sum(p.numel() for p in model.parameters()))early stop at epoch 237, best validation loss 0.136
test accuracy: 0.960
trainable parameters: 82
Mini-batches of 32 and Adam reach a low validation loss in far fewer epochs than full-batch gradient descent did, and patience 20 stops the run at epoch 237. The test split is the same as in the NumPy version, so 0.960 here and 0.970 there differ by one point out of 100: a tie.
Advantages and limits
| Advantages | Limits |
|---|---|
| No dependence on someone else's weights, licence or biases | Needs the most labelled data of any strategy |
| The architecture can fit the data exactly (input size, channels, latency budget) | The most compute: every feature is learned from zero |
| Nothing hidden: every behaviour comes from your data | Large models from scratch are unstable without careful initialisation, normalisation and learning-rate warm-up |
| Simple to reproduce: seed, data, code | On small data sets it overfits where a pretrained model would not |
Training from scratch is the default for tabular data (gradient-boosted trees and small MLPs rarely gain from pretraining), for small models on narrow tasks, and for pretraining itself: somebody trained resnet18 and BERT from scratch first.
Pitfalls
- Preprocessing fitted on all the data. The scaler in step 3 uses the training rows only, or the validation score is optimistic.
- Looking at the test set during tuning. Every decision you make after seeing a test score turns the test set into a second validation set.
- No baseline. A network at 0.85 accuracy is impressive only if the majority class is not already 0.85.
- Forgetting to restore the best weights. Early stopping detects the best epoch; the weights at the last epoch are worse.
- Unseeded runs. Without fixed seeds two runs differ, and you cannot tell a real improvement from luck. Better still, report the mean and spread over a few seeds.
Practice
- In the NumPy example, how many trainable parameters does the network have?
- Why does the NumPy loop compute the validation loss every epoch but the test accuracy only once?
- Change the NumPy example's hidden size to 2. What do you expect, and why?
Answers
- has , 16, has , 2: 82 parameters, the count PyTorch prints for the same layers. scikit-learn prints 65 because its binary classifier has one output unit.
- The validation set is used to make choices (the stopping epoch). The test set must not influence any choice, so it is used once, after all choices are made.
- Two tanh units can only bend the boundary a little, so the model underfits the moons: accuracy drops towards that of a linear model.
Test yourself
In which step of the workflow is the scaler fitted, and on which data?
- Step 2, on all the data
- Step 3, on the training set only
- Step 6, on the validation set
- Step 7, on the test set
Why are weights initialised with a variance like instead of all zeros?
- Zeros would make training faster
- With all-zero weights every hidden unit computes the same thing and gets the same gradient, so they never differ; the scale keeps activations from exploding or vanishing
- To save memory
- Because biases must be random
For which project is training from scratch usually the best choice?
- Classifying 500 photos of dogs with ImageNet models available
- A churn model on a table of 40 customer features
- Answering questions about legal contracts with a few hundred examples
- Detecting cars in dashcam video with a small labelled set
Early stopping found the best validation loss at epoch 120, and training stopped at epoch 140. Which weights do you keep?
- Epoch 140
- Epoch 120
- The average of both
- Epoch 1