在使用 PyTorch 深度学习框架时,可以通过将指定层放在 nn.Module 中,然后在计算图中重复调用该层来解决这个问题。在使用多个层堆叠起来的模型时,可以在模型构建中重复使用同一层。
代码示例:
import torch.nn as nn
class MyModel(nn.Module): def init(self): super(MyModel, self).init() self.linear1 = nn.Linear(100, 50) self.linear2 = nn.Linear(50, 10)
def forward(self, x):
x = nn.functional.relu(self.linear1(x))
x = nn.functional.dropout(x)
x = nn.functional.relu(self.linear1(x)) # 重复使用同一层
x = nn.functional.dropout(x)
x = self.linear2(x)
return x
model = MyModel() input_tensor = torch.randn(1, 100) output = model(input_tensor)
下一篇:Autograd行为澄清