文章目录
创建全连接层
在深度学习中,全连接层(Fully Connected Layer)或线性层(Linear Layer)是神经网络中的基本组成部分。PyTorch 提供了一个简单的接口来定义和使用这些层,即 torch.nn.Linear
。
全连接层(线性层)
一个全连接层将每个输入与每个输出连接起来,通常伴随着一个权重矩阵和一个偏置项。其计算公式为:
output = input × weight T + bias \text{output} = \text{input} \times \text{weight}^T + \text{bias} output=input×weightT+bias
其中:
- input \text{input} input是输入张量。
- weight \text{weight} weight 是权重矩阵。
- bias \text{bias} bias 是偏置项(可选)。
使用 PyTorch 定义全连接层
在 PyTorch 中,全连接层由 torch.nn.Linear
类表示。
1. 定义一个全连接层
import torch
import torch.nn as nn
# 定义一个输入维度为 4,输出维度为 2 的全连接层
fc = nn.Linear(in_features=4, out_features=2)
2. 查看层的参数
你可以查看全连接层的权重和偏置参数:
print("权重矩阵:\n", fc.weight)
print("偏置项:\n", fc.bias)
3. 使用全连接层
你可以将输入数据传递给全连接层进行前向传播(forward pass):
# 创建一个输入张量,形状为 (batch_size, in_features)
input_tensor = torch.tensor([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0,