¿Cuándo Pytorch comienza a llamar hacia adelante?

import torch
from torch import nn

class MLP(nn.Module):
    # 声明带有模型参数的层,这里声明了两个全连接层
    def __init__(self, **kwargs):
        # 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数
        # 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数params
        super(MLP, self).__init__(**kwargs)
        self.hidden = nn.Linear(784, 256) # 隐藏层
        self.act = nn.ReLU()
        self.output = nn.Linear(256, 10)  # 输出层


    # 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
    def forward(self, x):
        print('调用forward函数')
        a = self.act(self.hidden(x))
        return self.output(a)




X = torch.rand(2, 784)
net = MLP() # 多层感知机,网络结构的初始化。

print(net)
print('*'*50)
net(X)

MLP(
  (hidden): Linear(in_features=784, out_features=256, bias=True)
  (act): ReLU()
  (output): Linear(in_features=256, out_features=10, bias=True)
)
**************************************************
调用forward函数

Supongo que te gusta

Origin blog.csdn.net/gz153016/article/details/112726629
Recomendado
Clasificación