Understanding Feedforward Neural Networks
How a feedforward neural network turns inputs into predictions, why it needs nonlinear activations, how it learns, and when to use one.
Every network in this series, from the convolutional networks that read images to the recurrent ones that read text, is built from the same parts as the simplest kind: the feedforward network. Data enters at one end, passes through a few layers of weighted sums and simple nonlinear functions, and comes out the other end as a prediction. Nothing loops back.
If you followed the previous series, you already know most of the ingredients. Logistic regression is a weighted sum passed through a sigmoid. A feedforward network stacks several of those sums on top of each other, with a nonlinearity in between, and learns all the weights at once. That small change is what lets it fit curved boundaries that a linear model can’t.
This article builds a feedforward network from the ground up: one neuron, then a layer, then a full forward pass you can check by hand. It then shows why the nonlinearity matters, how training works, and what happens when you run a small network against logistic regression on the same data.
From one neuron to a network
A single neuron
A neuron (also called a unit) does two things. It computes a weighted sum of its inputs plus a bias, then passes the result through an activation function:
z = w1*x1 + w2*x2 + ... + wn*xn + b
a = activation(z)
The weights w say how much each input matters and in which direction. The bias b shifts the result up or down. If the activation is a sigmoid, this single neuron is exactly logistic regression. Everything else in a feedforward network is a way of arranging many of these.
Layers
A layer is a group of neurons that all read the same inputs. Each neuron has its own weights, so a layer with four neurons reading three inputs has a 4 by 3 weight matrix and four biases. Computing the whole layer is one matrix multiplication: a = activation(W @ x + b).
A feedforward network chains layers together:
- The input layer is just the features. It does no computation.
- One or more hidden layers transform the data. They are called hidden because you never see their target values; the network decides what they should represent.
- The output layer produces the prediction. Its size and activation depend on the task.
Each layer takes the previous layer’s output as its input. In the most common form, every neuron in one layer connects to every neuron in the next, which is why these are called fully connected or dense layers. A network with at least one hidden layer is often called a multilayer perceptron (MLP), a name that survives from the perceptron of the 1950s covered in the history of AI.
flowchart LR
x1["x1"] --> h1["h1"]
x1 --> h2["h2"]
x1 --> h3["h3"]
x1 --> h4["h4"]
x2["x2"] --> h1
x2 --> h2
x2 --> h3
x2 --> h4
x3["x3"] --> h1
x3 --> h2
x3 --> h3
x3 --> h4
h1 --> y["output"]
h2 --> y
h3 --> y
h4 --> y
That diagram is a 3-4-1 network: three inputs, one hidden layer of four units, one output. Every arrow is a weight, so there are 3 x 4 + 4 x 1 = 16 weights plus 5 biases, for 21 parameters.
What “feedforward” means
Information moves in one direction, from inputs to outputs, with no cycles. The output for one example depends only on that example’s inputs, not on anything the network saw before. That is the difference from recurrent networks, which feed a hidden state back into themselves so they can process sequences. Convolutional networks are also feedforward; they just replace some dense layers with layers that share weights across positions in an image.
The forward pass, by hand
The forward pass is the computation that turns one input into one prediction. Here is the 3-4-1 network above with concrete weights, a ReLU activation in the hidden layer and a sigmoid at the output:
import numpy as np
def relu(z):
return np.maximum(0, z)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
x = np.array([0.5, -1.0, 2.0]) # one example, 3 features
W1 = np.array([[ 0.2, -0.4, 0.1],
[ 0.7, 0.3, -0.2],
[-0.5, 0.6, 0.4],
[ 0.1, 0.1, 0.3]]) # 4 hidden units x 3 inputs
b1 = np.array([0.0, 0.1, -0.1, 0.2])
W2 = np.array([[0.6, -0.3, 0.8, 0.5]]) # 1 output x 4 hidden units
b2 = np.array([-0.2])
h = relu(W1 @ x + b1)
y_hat = sigmoid(W2 @ h + b2)
print("hidden:", h.round(3))
print("output:", y_hat.round(3))
hidden: [0.7 0. 0. 0.75]
output: [0.645]
You can check the first hidden unit yourself: 0.2 x 0.5 + (-0.4) x (-1.0) + 0.1 x 2.0 + 0.0 = 0.7, and ReLU leaves a positive number alone. The second unit’s sum is -0.25, so ReLU sets it to zero, and the third works out to -0.15, also zeroed. The output neuron then computes 0.6 x 0.7 + 0.5 x 0.75 - 0.2 = 0.595, and the sigmoid turns that into a probability of about 0.645.
Two hidden units output zero for this input. That is normal with ReLU: different inputs switch different units on and off, and that switching is how the network carves the input space into regions.
In practice you pass a whole batch at once. Stack the examples as rows of a matrix X, and the same code becomes relu(X @ W1.T + b1), computing every example’s hidden layer in one multiplication. That is why neural networks run so well on GPUs, which are built for large matrix multiplications.
Why the activation function matters
Remove the activation from the hidden layer and something surprising happens: the network collapses into a linear model. Two linear layers in a row compute W2 @ (W1 @ x + b1) + b2, which simplifies to (W2 @ W1) @ x + (W2 @ b1 + b2), a single weight matrix and a single bias. Stack a hundred linear layers and you still have one. Depth buys nothing without a nonlinearity between the layers.
The nonlinearity is what lets a network bend its decision boundary. The classic demonstration is XOR: output 1 when exactly one of two inputs is 1. No straight line separates the two classes, so logistic regression can’t learn it:
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
model = LogisticRegression().fit(X, y)
print(model.predict_proba(X)[:, 1].round(3), model.score(X, y))
[0.5 0.5 0.5 0.5] 0.5
The best it can do is predict 0.5 for everything. A network with one small hidden layer solves it, as the training example below shows.
Common activation functions
| Activation | Formula | Output range | Typical use | Watch out for |
|---|---|---|---|---|
| ReLU | max(0, z) | 0 to infinity | Default for hidden layers | Units can get stuck at zero (“dead” units) |
| Leaky ReLU | z if positive, else 0.01z | Unbounded | Hidden layers, when dead units are a problem | One more hyperparameter |
| GELU | z times the normal CDF of z | Roughly -0.17 to infinity | Hidden layers in transformers | Slightly more compute than ReLU |
| tanh | (e^z - e^-z) / (e^z + e^-z) | -1 to 1 | Small networks, recurrent networks | Gradients shrink for large inputs |
| Sigmoid | 1 / (1 + e^-z) | 0 to 1 | Output for binary classification | Same shrinking gradients as tanh in hidden layers |
| Softmax | e^zi / sum of e^zj | 0 to 1, sums to 1 | Output for multiclass classification | Only meaningful across a whole layer |
| None (identity) | z | Unbounded | Output for regression | Never between hidden layers |
The output activation follows from the task, the same way it did for the linear models: identity for regression, sigmoid for a yes-or-no label, softmax for one of several classes. Hidden layers are where you have a choice, and ReLU is the usual starting point because it is cheap and its gradient doesn’t shrink for positive inputs.
You build a network with five hidden layers but forget to add any activation functions. What can it represent?
Correct! A chain of linear layers multiplies out to one weight matrix and one bias, so the extra layers add nothing.
How much can one hidden layer do?
The universal approximation theorem says that a feedforward network with a single hidden layer and a suitable nonlinear activation can approximate any continuous function on a bounded input range as closely as you like, given enough hidden units. It is a reassuring result, but read it carefully. It says such a network exists; it says nothing about how many units you need, or whether training will find the right weights. In practice, deeper networks with fewer units per layer often reach the same accuracy with far fewer parameters, which is one reason “deep” learning won out over very wide shallow networks.
How a feedforward network learns
Training uses the same loop as every model in the previous series: predict, measure the error, adjust the parameters to reduce it. The deep learning basics article covers the learning rate in more detail; this section shows how the pieces fit for a network.
flowchart TD
B["Batch of examples"] --> F["Forward pass: layer by layer"]
F --> L["Loss: compare prediction to label"]
L --> G["Backward pass: gradient for every weight"]
G --> U["Update: weight minus learning rate times gradient"]
U --> C{"Loss still improving?"}
C -->|Yes| B
C -->|No| S["Stop and evaluate on held-out data"]
Loss
The loss function turns “how wrong” into a number. For regression it is usually mean squared error. For classification it is cross-entropy (also called log loss), which heavily penalizes confident wrong answers. These are the same losses linear and logistic regression use.
Backpropagation
To improve the weights, the network needs the gradient of the loss with respect to every weight: which direction to nudge it, and how hard. Backpropagation computes all of those gradients in one backward sweep. It applies the chain rule of calculus, starting at the output and working back layer by layer, reusing the values saved during the forward pass. The cost of the backward pass is roughly the same order as the forward pass, which is what makes training networks with millions of weights practical.
You almost never write backpropagation yourself. Frameworks like PyTorch, TensorFlow and JAX record the forward computation and derive the gradients automatically. It is still worth seeing once, because it shows there is no magic involved.
Training a network from scratch
This script trains a 2-4-1 network on XOR using only NumPy: a tanh hidden layer, a sigmoid output, cross-entropy loss, and plain gradient descent on all four examples at once.
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
rng = np.random.default_rng(1)
W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros(4)
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros(1)
lr = 0.5
def sigmoid(z):
return 1 / (1 + np.exp(-z))
for step in range(5001):
# forward pass
z1 = X @ W1 + b1
h = np.tanh(z1)
p = sigmoid(h @ W2 + b2)
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
# backward pass: gradients of the loss for each parameter
dz2 = (p - y) / len(X)
dW2 = h.T @ dz2; db2 = dz2.sum(axis=0)
dz1 = (dz2 @ W2.T) * (1 - h ** 2)
dW1 = X.T @ dz1; db1 = dz1.sum(axis=0)
# gradient descent update
W1 -= lr * dW1; b1 -= lr * db1
W2 -= lr * dW2; b2 -= lr * db2
if step % 1000 == 0:
print(f"step {step:>4} loss {loss:.4f}")
print("predictions:", p.ravel().round(3))
step 0 loss 0.6712
step 1000 loss 0.0051
step 2000 loss 0.0024
step 3000 loss 0.0016
step 4000 loss 0.0012
step 5000 loss 0.0009
predictions: [0. 0.999 0.999 0.002]
The network has learned XOR. A few lines deserve a closer look:
dz2 = (p - y) / len(X)is the gradient of cross-entropy through a sigmoid. It is the same simple form you get in logistic regression.dz2 @ W2.Tsends the output error back to each hidden unit in proportion to the weight connecting them. That is the “back” in backpropagation.(1 - h ** 2)is the derivative of tanh. Each layer’s gradient is multiplied by its activation’s derivative on the way back.
Now change the seed from 1 to 0 and run it again. The loss stalls around 0.347 and the predictions come out as roughly 0, 0.5, 1 and 0.5: the network has settled into a solution that gets two examples right and gives up on the other two. Same data, same code, different starting weights. Unlike linear and logistic regression, a network’s loss surface has many low points, and gradient descent finds whichever one is downhill from where it started. That is why initialization schemes, careful learning rates and optimizers such as Adam exist, and why it is worth training more than once before concluding that a network doesn’t work.
What does backpropagation compute?
Correct! Backpropagation produces the gradients; the optimizer then uses them to update the weights.
A network against logistic regression
The choosing an ML algorithm article used make_moons, two interleaved half circles, to show where linear models fall short. Here is the same dataset with scikit-learn’s MLPClassifier, using the same five folds and a scaler in every pipeline:
from sklearn.datasets import make_moons
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
X, y = make_moons(n_samples=1000, noise=0.25, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
candidates = {
"logistic regression": LogisticRegression(),
"MLP, 1 hidden unit": MLPClassifier(hidden_layer_sizes=(1,), max_iter=2000, random_state=0),
"MLP, 8 hidden units": MLPClassifier(hidden_layer_sizes=(8,), max_iter=2000, random_state=0),
"MLP, 32 hidden units": MLPClassifier(hidden_layer_sizes=(32,), max_iter=2000, random_state=0),
"MLP, 32 x 32": MLPClassifier(hidden_layer_sizes=(32, 32), max_iter=2000, random_state=0),
}
for name, model in candidates.items():
pipe = make_pipeline(StandardScaler(), model)
scores = cross_val_score(pipe, X, y, cv=cv)
print(f"{name:<22} {scores.mean():.3f} +/- {scores.std():.3f}")
With scikit-learn 1.9, the output is:
logistic regression 0.849 +/- 0.027
MLP, 1 hidden unit 0.848 +/- 0.023
MLP, 8 hidden units 0.850 +/- 0.022
MLP, 32 hidden units 0.936 +/- 0.010
MLP, 32 x 32 0.937 +/- 0.009
MLPClassifier defaults to ReLU hidden units, the Adam optimizer and a small L2 penalty (alpha=0.0001), and uses a sigmoid output for a binary label. The results say several things:
- One hidden unit is logistic regression with extra steps. A single ReLU unit feeding a sigmoid can only draw one boundary, and the scores match.
- Thirty-two units beat logistic regression by almost nine points, matching the RBF SVM and k-NN results from the comparison article. The network learned the curve.
- A second hidden layer adds nothing here. Two input features and one curved boundary don’t need depth. Depth pays off when the data has structure built from parts, like pixels forming edges forming shapes, which is the subject of the next articles in this series.
- Eight units did no better than one, which looks odd. Eight ReLU units are enough to trace this boundary, so the problem is training, not capacity.
Small networks and starting points
To see what happened with eight units, train each size five times with different random seeds and look at training accuracy:
import warnings
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
warnings.filterwarnings("ignore")
X, y = make_moons(n_samples=1000, noise=0.25, random_state=0)
X = StandardScaler().fit_transform(X)
for units in (4, 8, 32):
scores = []
for seed in range(5):
m = MLPClassifier(hidden_layer_sizes=(units,), max_iter=2000, random_state=seed)
scores.append(m.fit(X, y).score(X, y))
print(f"{units:>2} units: " + " ".join(f"{s:.3f}" for s in scores))
4 units: 0.853 0.940 0.865 0.859 0.873
8 units: 0.855 0.940 0.854 0.938 0.864
32 units: 0.936 0.938 0.939 0.939 0.940
Four units can reach 0.940 when the starting weights are lucky, but usually don’t. Eight units find the good solution two times in five. Thirty-two units find it every time. This is the XOR seed problem again, at a larger scale: small networks have few paths to a good solution, and some starting points lead nowhere. A network somewhat larger than the minimum is easier to train, and regularization plus early stopping keep the extra capacity from turning into overfitting.
Scaling matters
Like SVMs and k-NN, neural networks are sensitive to feature scale. Large raw inputs produce large weighted sums, which push the optimizer around and slow it down. On the breast cancer dataset from the comparison article, a 32-unit MLPClassifier scores 0.951 on raw features and 0.975 with a StandardScaler in the pipeline, using the same folds. Standardize inputs before training a network, and fit the scaler inside the pipeline so nothing leaks from the validation folds.
The knobs you will tune
| Hyperparameter | What it controls | Starting point | Too small | Too large |
|---|---|---|---|---|
| Hidden layers | Depth | 1 or 2 for tabular data | Can’t fit the pattern | Slower, harder to train, little gain on simple data |
| Units per layer | Width | 32 to 256 | Underfits, sensitive to seeds | Overfits without regularization |
| Activation | Nonlinearity in hidden layers | ReLU | Not applicable | Not applicable |
| Learning rate | Step size of each update | 0.001 with Adam | Training crawls | Loss jumps around or diverges |
| Batch size | Examples per update | 32 to 256 | Noisy updates, slow per epoch | Uses more memory, may generalize slightly worse |
| Epochs | Passes over the data | Until validation loss stops improving | Underfits | Overfits |
| L2 penalty or dropout | Regularization | Small L2; dropout of 0.1 to 0.5 in larger networks | Overfits | Underfits |
Two habits save a lot of time. First, hold out a validation set and watch its loss during training; stop when it stops improving (early_stopping=True in scikit-learn, or an early stopping callback in Keras). Second, change one thing at a time. Networks have enough knobs that changing three at once makes it impossible to tell which one helped. The model training and evaluation article covers validation sets and overfitting in general.
When to use a feedforward network
A feedforward network is a flexible function approximator, but flexible is not the same as best.
On tabular data (rows and columns, like most business datasets), gradient-boosted trees usually match or beat an MLP with less tuning, no scaling and better handling of missing values. A small network is still a reasonable candidate in a comparison, and it does well when features are smooth numeric measurements. Compare it fairly against a linear model and a tree ensemble before committing.
On images, audio and text, plain feedforward networks are rarely used on the raw input. A 224 by 224 color image has 150,528 values; a dense layer of 1,000 units on top of it would need over 150 million weights and would ignore the fact that neighboring pixels are related. Convolutional and recurrent networks, and transformers, add structure that suits those inputs. They still contain dense layers: the final classification layers of most image models are a small feedforward network, and each transformer block includes a two-layer feedforward network applied to every token.
On embeddings, a feedforward network is often exactly right. When you already have a dense vector for each item, from a pretrained model, a small MLP on top is a common and effective classifier. That is a lighter alternative to the full fine-tuning of a pre-trained model.
| Situation | Feedforward network? | Usually better first choice |
|---|---|---|
| Tabular data, a few thousand rows | Worth comparing | Logistic regression, gradient boosting |
| Tabular data, millions of rows, smooth numeric features | Good candidate | Gradient boosting as the benchmark |
| Raw images | No, not on its own | Convolutional network or pretrained vision model |
| Text or sequences | No, not on its own | Transformer or recurrent network |
| Classifying precomputed embeddings | Yes | Logistic regression as the baseline |
| Must explain each decision | Hard to justify | Linear model or shallow tree |
Running it in the cloud
A model like the ones above trains in seconds on a laptop CPU, and scikit-learn is enough. Once you move to larger networks you will use a deep learning framework, where the same 2-32-1 network is a few lines:
import torch.nn as nn
model = nn.Sequential(
nn.Linear(2, 32),
nn.ReLU(),
nn.Linear(32, 1), # pair with nn.BCEWithLogitsLoss, which applies the sigmoid
)
In Keras the equivalent layer is Dense; implementing a network in TensorFlow is a later article in this series. When a model outgrows one machine, or you want managed experiment tracking and GPUs on demand, the managed ML platforms (Amazon SageMaker AI, Vertex AI and Azure Machine Learning) run training jobs from your own PyTorch or TensorFlow code in prebuilt containers. The setting up a simple ML project article compares them. GPU time bills by the hour, so for networks this size, a CPU is the cheaper and perfectly adequate choice.
Further reading:
- scikit-learn: neural network models (supervised)
- PyTorch: torch.nn.Linear
- Keras: Dense layer
- For a broader introduction, see understanding neural networks.
Key takeaways
- A feedforward network is layers of weighted sums and nonlinear activations, with data flowing one way from inputs to output. A single sigmoid neuron is logistic regression.
- Without activation functions between layers, any number of layers collapses into one linear model. The nonlinearity is what lets the network fit curves and patterns like XOR.
- Use ReLU in hidden layers to start; pick the output activation from the task: identity for regression, sigmoid for binary, softmax for multiclass.
- Training repeats forward pass, loss, backpropagation and a gradient step. Backpropagation computes every weight’s gradient in one backward sweep, and frameworks do it for you.
- A network’s result depends on its starting weights. Small networks often get stuck; a somewhat larger network with regularization and early stopping trains more reliably.
- Standardize inputs, use a validation set, and change one hyperparameter at a time.
- On tabular data, compare a network against a linear model and gradient boosting before choosing it. On images and text, specialized architectures do better, though they still contain feedforward layers.