Fully connected layer

Also known as: dense layer · linear layer

On this page 8

A fully connected layer is a neural network layer in which every input unit is connected to every output unit by its own learned weight. It computes an affine transformation, a matrix multiplication plus a bias vector, and is usually followed by a nonlinear activation function. In neural networks, it is also called a dense layer or a linear layer, the names used by Keras and PyTorch respectively.

Fully connected layers form the whole of a classic multilayer perceptron, the classification head of many convolutional networks and the feedforward block inside every transformer. They are simple and expressive, but their parameter count grows with the product of input and output sizes, which makes them the dominant source of weights in many large models.

How a fully connected layer computes its output

A fully connected layer maps an input vector x of length n to an output vector y of length m with the formula y = Wx + b, where W is an m x n weight matrix and b is a bias vector of length m. Each output element is a weighted sum of all inputs plus its own bias, which is exactly the computation of m artificial neurons working in parallel.

In practice, inputs arrive in batches, so the layer performs a matrix-matrix multiplication that maps well onto GPU and TPU hardware. The output then usually passes through an activation such as ReLU, GELU or a sigmoid. Without that nonlinearity, any stack of linear layers collapses into a single linear map, no matter how many layers it contains.

The table below lists the components of the layer and their roles.

ComponentShapeRole
Input vectornFeatures from the previous layer
Weight matrixm x nLearned connection strengths
Bias vectormShifts each output independently
Activation functionElementwiseAdds nonlinearity
Output vectormFeatures passed to the next layer
Components of a fully connected layer

Parameters, compute and memory

A fully connected layer has n x m weights plus m biases. This quadratic growth is the defining cost of the layer: doubling both the input and output width quadruples the number of weights. The forward pass needs about 2 x n x m floating-point operations per input example.

The following examples show how quickly the numbers rise in realistic configurations.

ConfigurationInput sizeOutput sizeParameters
MNIST hidden layer784128About 100,000
VGG-16 first dense layer25,0884,096About 103 million
Transformer feedforward expansion4,09616,384About 67 million
Classification head2,0481,000About 2 million
Parameter counts of typical fully connected layers

The VGG-16 example illustrates a well-known imbalance: its first dense layer alone holds more than 70 percent of the network weights. Later architectures such as ResNet replaced most dense layers with global average pooling followed by a single small classifier, cutting parameters sharply with little loss in accuracy.

How dense layers compare with other layer types

The fully connected layer makes no assumption about the structure of its input, which is both its strength and its weakness. Convolutional and recurrent layers build in an inductive bias through weight sharing, while attention layers compute connection strengths dynamically from the data.

Layer typeConnectivityWeight sharingBest suited to
Fully connected layerEvery input to every outputNoneFixed-size feature vectors
Convolutional layerLocal receptive fieldAcross spatial positionsImages and grids
Recurrent layerSequential stateAcross time stepsOrdered sequences
Self-attention layerAll positions, data-dependentProjection weights sharedSequences with long-range links
Fully connected layer compared with related layers

A convolution can be viewed as a fully connected layer with most weights forced to zero and the rest tied together. Conversely, a 1 x 1 convolution is a dense layer applied at every position, and the projection matrices inside attention are themselves linear layers. This is why fully connected layers appear in nearly every modern architecture, even when they are not named in it.

Fully connected layers inside transformers

Each transformer block contains a position-wise feedforward network made of two or three fully connected layers applied independently to every token. The first layer usually expands the width by a factor of about 4, an activation such as GELU or SwiGLU follows, and the last layer projects back to the model width.

These feedforward layers hold roughly two-thirds of the parameters in a standard dense transformer, and research suggests they store much of the model factual associations. In a mixture-of-experts model, the single feedforward block is replaced by many parallel expert blocks, each one a small set of fully connected layers, with a router choosing which experts process each token.

Training, initialization and regularization

Fully connected layers train well only with sensible weight initialization. Xavier initialization scales weights to the average of input and output sizes and suits tanh or sigmoid activations, while He initialization accounts for the halving effect of ReLU. Poor initialization causes vanishing or exploding activations in deep stacks.

Because they hold so many parameters, dense layers are prone to overfitting on small datasets. Common remedies are listed below.

ProblemLikely causeCommon fix
OverfittingToo many weights for the dataDropout or weight decay
Slow or unstable trainingPoor weight scaleHe or Xavier initialization
Dead unitsLarge negative ReLU inputsLeaky ReLU or lower learning rate
Excessive memory useVery wide layersPooling, low-rank factorization or quantization
Typical problems with dense layers and their fixes

Dropout rates of 0.2 to 0.5 were standard for dense heads in convolutional networks. In large transformers, dropout is often reduced or removed, and normalization layers together with weight decay provide most of the stabilization.

Limitations of fully connected layers

  • They require a fixed input size, so images or sequences must be flattened, pooled or padded first.
  • Flattening an image discards spatial structure, which a convolution would preserve.
  • The quadratic parameter growth makes very wide layers expensive in memory and bandwidth.
  • Inference on large dense layers is often limited by memory bandwidth rather than arithmetic.

These limits explain why dense layers are rarely used on raw high-dimensional inputs today. They are most effective after other layers have extracted compact features, where their flexibility to combine any feature with any other is valuable.

The simple explanation

A fully connected layer is a group of small calculators. Each one looks at every piece of the input. It gives each piece a weight, adds everything up and passes the result on.

Imagine a panel of judges scoring a dish. Every judge tastes every ingredient. Each judge cares about some ingredients more than others. Training is how the network learns what each judge should care about. The catch is size. Many judges and many ingredients mean a very large number of weights to learn.

How it is used in practice

A retail company builds an image classifier to sort product photos into 120 catalog categories. The engineers start from a convolutional network pretrained on a large image dataset and keep its feature extractor, which outputs a 2,048-value feature vector for each photo after global average pooling.

They replace the original classification head with a new fully connected layer of size 2,048 x 120, about 246,000 parameters, and train only that layer first on 30,000 labeled photos. Because the dense head is small, training takes minutes on one GPU. After the head converges, they fine-tune the last convolutional stage as well. The final model reaches the accuracy the team needs while training less than one percent of the network in the first stage, which keeps the risk of overfitting low.