Parameters and Initialisation
Training is a search through parameter space, and every search needs a starting point. For a convex model such as logistic regression the start hardly matters: there is one minimum and gradient descent finds it from anywhere. For a neural network the start decides whether training works at all. Start every weight at zero and the hidden units never learn different things. Start them too small and the signal fades to nothing after a few layers; too large and it explodes. This lesson covers the first two of the training concepts: what the parameters are, and how to initialise them.
Parameters and hyperparameters
| Parameters | Hyperparameters | |
|---|---|---|
| What | the numbers the model learns: weights and biases | the settings you choose before training |
| Set by | the optimizer, from the gradient | you, by experience or tuning |
| Examples | , , a tree's split thresholds | learning rate, batch size, number of layers, hidden width, weight decay |
| Saved in | the checkpoint (state_dict) |
the training configuration |
A dense layer from to units has weights and biases. The parameter count of an MLP is the sum over its layers:
The count drives memory (4 bytes per parameter in float32, plus as much again for each optimizer state such as Adam's two moments), and, together with the amount of data, how easily the model can memorise. More counting rules (convolutions, attention) are in Counting Parameters and FLOPs.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.neural_network import MLPClassifier
def n_params(sizes):
return sum(a * b + b for a, b in zip(sizes[:-1], sizes[1:]))
for sizes in ([2, 16, 1], [784, 128, 64, 10], [3072, 1024, 1024, 10]):
n = n_params(sizes)
print(f"{str(sizes):22s} {n:>9,d} parameters {n * 4 / 1e6:6.2f} MB in float32")
X, y = make_moons(n_samples=200, noise=0.25, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(16,), max_iter=2000, random_state=0).fit(X, y)
count = sum(W.size for W in mlp.coefs_) + sum(b.size for b in mlp.intercepts_)
print("scikit-learn MLP (2-16-1) parameters:", count, " shapes:", [W.shape for W in mlp.coefs_])[2, 16, 1] 65 parameters 0.00 MB in float32
[784, 128, 64, 10] 109,386 parameters 0.44 MB in float32
[3072, 1024, 1024, 10] 4,206,602 parameters 16.83 MB in float32
scikit-learn MLP (2-16-1) parameters: 65 shapes: [(2, 16), (16, 1)]
The moons network of the previous lessons has 65 parameters; a small image classifier for 28 by 28 digits already has 109,386, and two hidden layers of 1024 units on 32 by 32 colour images ( inputs) take 4.2 million, almost all of them in the first layer. scikit-learn's MLPClassifier stores the same 65 numbers as two weight matrices in coefs_ and two bias vectors in intercepts_.
Why not start at zero?
Suppose every weight of a hidden layer starts at the same value. Then every hidden unit computes the same function of the input, receives the same gradient in backprop, and gets the same update. After any number of steps they are still identical: 16 hidden units behave like one. This is the symmetry problem, and random initialisation exists to break it.
import numpy as np
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=200, noise=0.25, random_state=0)
X = (X - X.mean(axis=0)) / X.std(axis=0)
def train(W1, w2, steps=500, lr=0.5):
b1, b2 = np.zeros(W1.shape[1]), 0.0
for _ in range(steps): # full-batch gradient descent
A1 = X @ W1 + b1; H = np.maximum(0, A1)
p = 1 / (1 + np.exp(-(H @ w2 + b2)))
dz = (p - y) / len(y)
dA1 = np.outer(dz, w2) * (A1 > 0)
W1, b1 = W1 - lr * X.T @ dA1, b1 - lr * dA1.sum(axis=0)
w2, b2 = w2 - lr * H.T @ dz, b2 - lr * dz.sum()
acc = np.mean((p >= 0.5) == y)
return W1, acc
W1, acc = train(np.full((2, 4), 0.5), np.full(4, 0.5)) # every weight 0.5
print("constant start, hidden weights (one column per unit):")
print(W1.round(3))
print("accuracy", acc)
rng = np.random.default_rng(0)
W1, acc = train(rng.normal(0, 1, (2, 4)), rng.normal(0, 0.5, 4))
print("random start, hidden weights:")
print(W1.round(3))
print("accuracy", acc)constant start, hidden weights (one column per unit):
[[ 0.295 0.295 0.295 0.295]
[-0.602 -0.602 -0.602 -0.602]]
accuracy 0.835
random start, hidden weights:
[[ 1.835 0.219 0.34 -1.353]
[-0.647 0.932 1.348 0.683]]
accuracy 0.9
After 500 steps of full-batch gradient descent the four hidden units that started at 0.5 are still four copies of one unit: every column is . The network can only draw the boundary one ReLU unit allows and reaches 0.835 training accuracy. With a random start the units diverge into four different directions and the same training reaches 0.9.
Keeping the signal alive: Xavier and He
Even random weights can fail if their scale is wrong. Consider one unit with independent zero-mean weights and inputs. Its variance is
so each layer multiplies the variance by . If that factor is 0.5, after 10 layers the signal is times as large; if it is 2, it is about 1000 times larger. The gradients flowing backwards are scaled the same way, which is the vanishing and exploding gradient problem. The fix is to choose so the factor is 1:
| Scheme | Use with | |
|---|---|---|
| Xavier / Glorot | (about ) | tanh, sigmoid, linear layers |
| He / Kaiming | ReLU and its variants |
He has the extra factor 2 because ReLU sets half of its inputs to zero, which halves the second moment of the output. The full argument is in Initialisation. Watch it happen in a 10-layer ReLU network with 256 units per layer:
import numpy as np
rng = np.random.default_rng(0)
x0 = rng.normal(size=(1000, 256)) # 1000 inputs, unit variance
schemes = {"small (sd 0.01)": lambda n_in, n_out: 0.01,
"Xavier": lambda n_in, n_out: np.sqrt(2 / (n_in + n_out)),
"He": lambda n_in, n_out: np.sqrt(2 / n_in)}
for name, sd in schemes.items():
h, stds = x0, []
for layer in range(10):
W = rng.normal(0, sd(256, 256), (256, 256))
h = np.maximum(0, h @ W) # ReLU layer, no bias
stds.append(h.std())
print(f"{name:16s} activation sd after layers 1, 2, 5, 10:", " ".join(f"{stds[i]:.3g}" for i in (0, 1, 4, 9)))small (sd 0.01) activation sd after layers 1, 2, 5, 10: 0.094 0.0103 1.59e-05 3.04e-10
Xavier activation sd after layers 1, 2, 5, 10: 0.587 0.422 0.147 0.0241
He activation sd after layers 1, 2, 5, 10: 0.826 0.838 0.992 0.985
With standard deviation 0.01 each layer multiplies the variance by , so the activations fall from 0.094 after layer 1 to after layer 10: the last layers receive inputs that are almost exactly zero, and their gradients vanish with them. Xavier was derived for symmetric activations; with ReLU its factor is about one half per layer, and the signal decays slowly (0.587 to 0.0241). He initialisation keeps the activation scale near 1 through all ten layers (0.826 to 0.985), which is why it is the default choice for ReLU networks.
In the libraries
You rarely write the initialisation yourself: every layer comes with a sensible default.
- scikit-learn
MLPClassifierdraws uniform weights in , which is Xavier with a uniform distribution (for logistic activations the bound is multiplied by ). - PyTorch
nn.Lineardraws from a uniform distribution in (a Kaiming-uniform variant). To use He initialisation explicitly:nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")andnn.init.zeros_(layer.bias). - Biases usually start at zero; the random weights already break the symmetry.
- Very deep networks add normalisation layers and residual connections (Residual Connections), which make them much less sensitive to the initial scale.
Pitfalls
- Same seed, different "random" models. Two runs with the same seed and code start from identical weights. Report results over several seeds when you compare models, because the start alone moves scores by a point or more.
- He initialisation with tanh (or Xavier with deep ReLU stacks): the factor per layer is 2 or 0.5 instead of 1, harmless for 2 layers and fatal for 20.
- Copying weights between differently sized layers. A checkpoint's parameter shapes must match the model; loading fails loudly in PyTorch, but hand-written NumPy code may broadcast silently.
Practice
- How many parameters does a 100-50-50-3 MLP have, and how much memory do they take in float32?
Answer
, , ; total parameters, bytes, about 31 kB.
- A layer has and uses ReLU. What standard deviation does He initialisation give its weights?
Answer
.
- In the symmetry example, the two input weights of each hidden unit stay equal to each other too. Why?
Answer
Each column started as . The gradient of column is , and all columns of are equal, so all columns get the same update. Within a column the two entries can differ (they depend on different input features); in the printed output they do, by the same amounts in every column.
Test yourself
What happens if every weight of a hidden layer starts at the same value?
- Training is faster
- All hidden units compute the same function and receive the same updates, so they stay identical
- The network cannot compute a forward pass
- Only the biases are updated
Which initialisation is designed for ReLU layers?
- Xavier/Glorot,
- He/Kaiming,
- All zeros
- Standard normal,
In a 10-layer ReLU network initialised with a tiny standard deviation such as 0.01, what happens to the activations?
- They stay about the same size
- They shrink towards zero layer after layer
- They explode
- They become exactly binary
Which of these is a hyperparameter, not a parameter?
- A weight in the first layer
- The bias of the output unit
- The learning rate
- A split threshold learned by a tree