PyTorch torch.nn.Linear function
PyTorch torch.nn Reference Manual
torch.nn.Linear is a module in PyTorch for creating fully connected layers (also called linear layers or affine transformations).
It is one of the most fundamental and widely used layers in neural networks, responsible for linearly transforming input features into the output feature space.
Function definition
torch.nn.Linear(in_features, out_features, bias=True)
Parameter Description:
in_features(int): the dimension of input features, i.e. the number of features output by the previous layer.out_features(int): the dimension of output features, i.e. the number of features output by this layer.bias(bool): Whether to add a bias term. Defaults toTrue. If set toFalse, the layer will not learn bias parameters.
property through the following steps:
weight(Tensor): learnable weight matrix of shape (out_features, in_features).bias(Tensor): learnable bias vector of shape (out_features,). Ifbias=False, this attribute does not exist.
Mathematical principle
nn.Linear The computation formula is as follows:
y = xA^T + b
Where:
xis the input tensor, of shape (..., in_features)Ais the weight matrix, of shape (out_features, in_features)bis the bias vector, of shape (out_features)yis the output tensor, of shape (..., out_features)
sign before positive numbers ... means the input can be a tensor of arbitrary dimensions, and the linear transformation is applied to the last dimension.
Usage examples
Example 1: Basic usage
Create a simple fully connected layer mapping 10-dimensional input to 5-dimensional output:
Example
import
torch
import
torch.
nn
as
nn
Create a linear layer: input 10 dimensions, output 5 dimensions
linear_layer
=
nn.
Linear
(
in_features
=
10
,
out_features
=
5
,
bias
=
True
)
Print the shapes of the weights and bias
(
"Weight shape:"
,
linear_layer.
weight
.
shape
)
torch.Size([5, 10])
(
"Bias shape:"
,
linear_layer.
bias
.
shape
)
torch.Size([5])
Create an input tensor: batch_size=3, feature dimension=10
input_tensor
=
torch.
randn
(
3
,
10
)
Forward propagation
output
=
linear_layer
(
input_tensor
)
(
"Input shape:"
,
input_tensor.
shape
)
torch.Size([3, 10])
(
"Output shape:"
,
output.
shape
)
torch.Size([3, 5])
(
"Output data:n"
,
output
)
The output is:
权重形状: torch.Size([5, 10])
偏置形状: torch.Size([5])
输入形状: torch.Size([3, 10])
输出形状: torch.Size([3, 5])
输出数据:
tensor([[-0.1838, 0.0607, -0.4879, 0.8981, -0.2098],
[ 0.1513, -0.1873, 0.1866, -0.2448, -0.6012],
[ 0.2915, 0.3053, 0.2532, -0.3372, -0.3968]],
grad_fn=)
In this example, we created a fully connected layer with 10-dimensional input and 5-dimensional output. The input tensor has shape (3, 10), where 3 is the batch size and 10 is the feature dimension. The output tensor has shape (3, 5).
Example 2: Without bias
Create a linear layer without a bias term:
Example
import
torch
import
torch.
nn
as
nn
Create a linear layer without bias
linear_no_bias
=
nn.
Linear
(
in_features
=
10
,
out_features
=
5
,
bias
=
False
)
Check whether bias exists
(
"Does bias exist:"
,
linear_no_bias.
bias
is
None
)
True
Forward propagation
input_tensor
=
torch.
randn
(
3
,
10
)
output
=
linear_no_bias
(
input_tensor
)
(
"Output shape:"
,
output.
shape
)
torch.Size([3, 5])
(
"Output:n"
,
output
)
The output is:
偏置是否存在: True
输出形状: torch.Size([3, 5])
输出:
tensor([[-0.3312, -0.4113, 0.0257, -0.4876, 0.0780],
[ 0.1513, 0.2459, -0.2983, 0.2456, -0.0727],
[-0.0143, 0.3053, 0.1866, -0.3372, 0.2532]],
grad_fn=)
Example 3: Multi-dimensional input
nn.Linear It can handle inputs of arbitrary dimensions and only transforms the last dimension:
Example
import
torch
import
torch.
nn
as
nn
Create a linear layer
linear
=
nn.
Linear
(
in_features
=
10
,
out_features
=
5
)
Handle 2D input (batch, features)
input_2d
=
torch.
randn
(
8
,
10
)
output_2d
=
linear
(
input_2d
)
(
"2D input -> output:"
,
input_2d.
shape
,
"->"
,
output_2d.
shape
)
Handle 3D input (batch, seq, features)
input_3d
=
torch.
randn
(
4
,
6
,
10
)
output_3d
=
linear
(
input_3d
)
(
"3D input -> output:"
,
input_3d.
shape
,
"->"
,
output_3d.
shape
)
Handle 4D input (batch, channels, height, width)
input_4d
=
torch.
randn
(
2
,
3
,
4
,
10
)
output_4d
=
linear
(
input_4d
)
(
"4D input -> output:"
,
input_4d.
shape
,
"->"
,
output_4d.
shape
)
The output is:
二维输入 -> 输出: torch.Size([8, 10]) -> torch.Size([8, 5])
三维输入 -> 输出: torch.Size([4, 6, 10]) -> torch.Size([4, 6, 5])
四维输入 -> 输出: torch.Size([2, 3, 4, 10]) -> torch.Size([2, 3, 4, 5])
Example 4: Using it in a neural network
In a real neural network,nn.Linear it is usually combined with other layers:
Example
import
torch
import
torch.
nn
as
nn
Define a multilayer perceptron (MLP)
class
MLP
(
nn.
Module
)
:
def
init
(
self
,
input_dim
,
hidden_dim
,
output_dim
)
:
super
(
MLP
,
self
)
.
init
(
)
First layer: input -> hidden layer
self
.
fc1
=
nn.
Linear
(
input_dim
,
hidden_dim
)
Activation function
self
.
relu
=
nn.
ReLU
(
)
Second layer: hidden layer -> output
self
.
fc2
=
nn.
Linear
(
hidden_dim
,
output_dim
)
def
forward
(
self
,
x
)
:
x
=
self
.
fc1
(
x
)
x
=
self
.
relu
(
x
)
x
=
self
.
fc2
(
x
)
return
x
Create the model
model
=
MLP
(
input_dim
=
784
,
hidden_dim
=
256
,
output_dim
=
10
)
Print the model structure
(
"Model structure:"
)
(
model
)
Test the forward pass
input_tensor
=
torch.
randn
(
32
,
784
)
batch_size=32, 28x28=784
output
=
model
(
input_tensor
)
(
"nInput shape:"
,
input_tensor.
shape
)
torch.Size([32, 784])
(
"Output shape:"
,
output.
shape
)
torch.Size([32, 10])
The output is:
Model structure:
MLP(
(fc1): Linear(in_features=784, out_features=256, bias=True)
(relu): ReLU()
(fc2): Linear(in_features=256, out_features=10, bias=True)
)
输入形状: torch.Size([32, 784])
输出形状: torch.Size([32, 10])
Weight initialization
By default,nn.Linear Use PyTorch's default initialization strategy.
You can also initialize weights manually:
Example
import
torch
import
torch.
nn
as
nn
Create a linear layer
linear
=
nn.
Linear
(
10
,
5
)
Initialize weights with Xavier initialization
nn.
init
.
xavier_uniform_
(
linear.
weight
)
Initialize the bias to zero
nn.
init
.
zeros_
(
linear.
bias
)
View the initialized weights
(
"Weights:n"
,
linear.
weight
.
data
)
(
"Bias:"
,
linear.
bias
.
data
)
Difference from nn.functional.linear
PyTorch also provides a functional interface torch.nn.functional.linear:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
Method 1: Using nn.Module
linear_module
=
nn.
Linear
(
10
,
5
)
output1
=
linear_module
(
torch.
randn
(
3
,
10
)
)
Method 2: Using the functional interface
weight
=
torch.
randn
(
5
,
10
)
bias
=
torch.
randn
(
5
)
output2
=
F.
linear
(
torch.
randn
(
3
,
10
)
,
weight
,
bias
)
(
"nn.Module output shape:"
,
output1.
shape
)
(
"nn.functional output shape:"
,
output2.
shape
)
The difference between the two:
nn.Linearis a module class that stores weight and bias parameters, making it easy to train and save the model.F.linearis a function that requires you to pass weights and bias manually, often used when there are no learnable parameters.
Note: although both perform the same mathematical operation, when building neural networks you usually use
nn.Linear, because it automatically registers parameters for easy optimizer updates.
Common questions
Q1: How to check the number of parameters in a Linear layer?
For a linear layer with (in_features, out_features):
- Number of weight parameters: in_features * out_features
- Number of bias parameters: out_features (if bias=True)
Example
import
torch
import
torch.
nn
as
nn
linear
=
nn.
Linear
(
100
,
50
)
(
"Total number of parameters:"
,
sum
(
p.
numel
(
)
for
p
in
linear.
parameters
(
)
)
)
(
"Weight parameters:"
,
linear.
weight
.
numel
(
)
)
(
"Bias parameters:"
,
linear.
bias
.
numel
(
)
)
Q2: How to freeze the parameters of a Linear layer?
If you want to keep certain layers from participating in training, you can set requires_grad=False:
Example
import
torch
import
torch.
nn
as
nn
linear
=
nn.
Linear
(
10
,
5
)
Freeze the weights so they do not participate in gradient computation
linear.
weight
.
requires_grad
=
False
Freeze the bias
linear.
bias
.
requires_grad
=
False
Validation
(
"Weight requires_grad:"
,
linear.
weight
.
requires_grad
)
(
"Bias requires_grad:"
,
linear.
bias
.
requires_grad
)
Use Cases
nn.Linear is one of the most commonly used layers in neural networks, with main application scenarios including:
- Multilayer perceptron (MLP): as a fully connected layer, mapping features to a new feature space.
- Classifier: using a fully connected layer at the end of convolutional or recurrent networks for classification.
- Feature transformation: applying a linear transformation to data for dimensionality reduction or expansion.
- Attention Mechanism: used in Transformers to generate the Q, K, V matrices.