Neural networks: the basics

Stack layers of weighted sums and simple non-linear functions, and train all the weights by repeated small corrections.

Lesson 33 of 6615 minIntermediate

You will learn to

  • Explain how a network turns inputs into a prediction layer by layer
  • Describe how training adjusts weights with gradient descent
  • Say when a small neural network is a reasonable choice for a table of data and what it needs

Before this lesson

Intuition

A single neuron is nothing more than what you already know: a weighted sum of the inputs, plus a bias. A neural network connects many of these neurons in layers. The first layer reads the inputs. Each neuron in the next layer reads all the outputs of the previous layer, and so on, until a final layer produces the prediction.

Alone, that would still be a linear model. The key ingredient is a small non-linear function applied to each neuron's sum, the activation. The popular choice, ReLU, simply replaces negative numbers by zero. A neuron then "switches on" only when its weighted sum is positive. With many such switches, a network can build curves, thresholds and interactions out of straight pieces. Early layers learn simple patterns, later layers combine them into more useful ones.

Nobody sets the weights by hand. They start as small random numbers and are trained: show the network a batch of rows, measure the error with a loss function, work out how each weight contributed to it, and nudge every weight slightly in the direction that lowers the error. Repeat thousands of times.

On tables of data, small networks are competitive but not usually better than boosted trees. Their strengths show on images, audio and text, which need much bigger networks than this lesson covers.

Picture it

x11x22h10.5h20p0.668InputsHidden layer (ReLU)Output (sigmoid)
A tiny network with two inputs, two hidden units and one output. The numbers are those of the worked example: the first hidden unit is active, the second is switched off by ReLU.

Every line is a weight. Signals flow from left to right, which is called the forward pass. Training flows backwards: the error at the output is passed back through the lines to tell each weight how to change (backpropagation).

The math

A layer with inputs xx, a weight matrix WW and a bias vector bb computes h=f(Wx+b)h = f(Wx + b), where ff is the activation. Two common activations are

ReLU(z)=max⁡(0,z),σ(z)=11+e−z\text{ReLU}(z) = \max(0, z), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}

For a classifier, the last layer uses the sigmoid (or softmax for more than two classes) so the output is a probability; for regression the last layer is a plain weighted sum.

Training minimises a loss, for example the log loss L=−ln⁡pL = -\ln p when the true class is positive. For each weight ww gradient descent applies

w←w−η ∂L∂ww \leftarrow w - \eta \,\frac{\partial L}{\partial w}

where η\eta is the learning rate and the derivative comes from the chain rule applied backwards through the layers. The number of weights is easy to count: a layer with mm inputs and nn neurons has mn+nm n + n parameters. A network with 10 inputs, hidden layers of 64 and 32 neurons and one output has (10 x 64 + 64) + (64 x 32 + 32) + (32 + 1) = 2,817 parameters. With that many parameters, networks overfit easily, so they use a penalty on the weights (alpha) and stop training when a validation score stops improving.

Worked example

Use the network in the picture, with illustrative weights. Inputs are x1 = 1 and x2 = 2.

  • Hidden unit 1: weights 0.5 and 0.25, bias -0.5. Sum = 0.5 x 1 + 0.25 x 2 - 0.5 = 0.5. ReLU leaves 0.5.
  • Hidden unit 2: weights -1 and -0.5, bias 0.2. Sum = -1 - 1 + 0.2 = -1.8. ReLU turns this into 0.
  • Output: weights 2 and 1, bias -0.3. Score z = 2 x 0.5 + 1 x 0 - 0.3 = 0.7. The sigmoid gives p = 1 / (1 + e^-0.7) = 0.668.

If the true class is positive, the loss is -ln(0.668) = 0.403. The gradient of the loss with respect to the output score is p - 1 = -0.332. The weight from hidden unit 1 receives the gradient -0.332 x 0.5 = -0.166, and the output bias receives -0.332. With a learning rate of 0.1, the weight moves from 2 to 2.017 and the bias from -0.3 to -0.267. (We update only these two numbers to keep the example short; a real step updates every weight.) The new score is 0.741, the probability rises to 0.677 and the loss falls to 0.390. The weight on hidden unit 2 gets no gradient for this row, because that unit was switched off.

A computed comparison shows why scaling matters. On a sample dataset with 768 rows, an MLP classifier with scikit-learn defaults (one hidden layer of 100 neurons, ReLU, up to 500 iterations) scored an accuracy of 0.659 in 5-fold stratified cross-validation (seed 42) on the raw columns, and training did not fully converge. With a standard scaler in front, it scored 0.745. Logistic regression on the same folds scored 0.775, so a bigger model is not automatically a better one.

How mlflow does it

The classification and regression algorithms are MLP Classifier and MLP Regressor (mlp), which train with up to 500 iterations. Their tunable parameters include the hidden layer sizes, activation, alpha (the weight penalty) and learning_rate. When the optional deep-learning packages are installed, PyTorch MLP (torch_mlp) and Keras MLP (keras_mlp) also appear, with a hidden_layers setting that defaults to 64,32 (two layers of 64 and 32 neurons). Add a scaler step before any network and encode categorical columns. Treat a network as one candidate in the run, and compare it with the simpler models on the leaderboard.

Common mistakes

  • Not scaling the inputs. Gradients become unbalanced and training is slow or stuck. Scale first.
  • Making the network large before trying a small one. Big networks overfit tables of a few thousand rows. Start with one or two small layers and a penalty.
  • Judging by the training loss. It almost always keeps falling. Compare cross-validated scores and watch for a gap.
  • Ignoring convergence warnings. A warning that training stopped at the iteration limit means the weights are not finished. Raise the iteration limit or scale the inputs.
  • Expecting a neural network to beat gradient boosting on a table by default. On tabular data the gain is not guaranteed. Let the leaderboard decide.

Try it in mlflow

Train a small neural network with and without scaling

  1. Open Pipelines and pick a classification or regression pipeline.
  2. Open the Models part and add MLP Classifier (or MLP Regressor).
  3. Click Train 1 algorithm and note the cross-validated score.
  4. Back in the pipeline, choose Standardise for the numeric columns (Columns part) and train again. The score usually improves clearly.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. Why does a network need a non-linear activation function such as ReLU between layers?
  2. 2. What does one step of gradient descent do?
  3. 3. You train a small neural network on a table with columns in very different scales and the score is poor. What is the first thing to try?