torch 前馈层定义
时间: 2023-07-19 09:07:31 浏览: 67
在 PyTorch 中,前馈层可以使用 torch.nn 中的 Linear 模块来定义。Linear 模块实现了全连接层的功能,它接收一个输入向量,并将其乘以一个权重矩阵,再加上一个偏置向量,最后输出一个新的向量。
下面是一个简单的前馈神经网络的示例代码,其中包含了三个全连接层:
```
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(in_features=10, out_features=20)
self.fc2 = nn.Linear(in_features=20, out_features=30)
self.fc3 = nn.Linear(in_features=30, out_features=2)
def forward(self, x):
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
x = nn.functional.relu(x)
x = self.fc3(x)
return x
```
在这个例子中,我们定义了一个名为 Net 的类,它继承自 nn.Module。在 __init__ 方法中,我们定义了三个 Linear 层,分别是 fc1、fc2 和 fc3,它们的输入和输出维度依次为(10,20)、(20,30)和(30,2)。在 forward 方法中,我们将输入 x 依次传入每个 Linear 层,并使用 ReLU 激活函数对输出进行非线性变换,最后返回输出向量。
阅读全文
相关推荐


















