Feature projection
Transforming representations between neural-network stages.
PyTorch · Class
torch.nn.Linear is a trainable affine layer that maps each input vector from in_features to out_features. It preserves all leading dimensions and can optionally include a learnable bias.
The module stores a weight matrix and, by default, a bias vector. For an input whose final dimension matches in_features, it computes an affine transformation and changes only that final dimension to out_features; leading dimensions are preserved.
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)| Name | Type | Description |
|---|---|---|
in_features | int | Size of each input sample. |
out_features | int | Size of each output sample. |
bias | bool | Whether to learn an additive bias; defaults to True. |
device | torch.device, optional | Optional device on which to create the module. |
dtype | torch.dtype, optional | Optional data type for the module’s parameters. |
A tensor with shape (*, out_features), where * represents the input’s unchanged leading dimensions.
import torch
from torch import nn
layer = nn.Linear(20, 30)
x = torch.randn(128, 20)
y = layer(x)
print(y.shape) # torch.Size([128, 30])Creates a trainable 20-to-30 affine layer and applies it to a batch whose final dimension has size 20.
Transforming representations between neural-network stages.
Producing logits or scores from a learned representation.
Changing the width of the final dimension in batched or sequence data.
It applies y = xAᵀ + b, where the learnable weight has shape (out_features, in_features). The input’s last dimension must equal in_features, and the output’s last dimension becomes out_features.
Follow-up: What happens to a batched or higher-rank input? Every dimension except the final one is retained, while the final dimension is replaced by out_features.
in_features is the size of each input sample, while out_features is the size of each output sample. bias controls whether the module includes a learnable additive bias and defaults to True.
Follow-up: How would you create a layer without an offset? Construct it with bias=False.
The weight is initialized from a uniform distribution whose bounds depend on the reciprocal of in_features. The module exposes weight with shape (out_features, in_features) and bias with shape (out_features).
Follow-up: What parameter shape should be expected when connecting this layer to a previous representation of width n? The weight’s second dimension should be n, so construct the layer with in_features=n.
torch.nn.Moduletorch.nn.LazyLineartorch.nn.Identitytorch.nn.Bilinear