jas*_*son 1 python class function pytorch
我有以下pytorch代码
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(784, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
x = F.sigmoid(self.hidden(x))
x = F.softmax(self.output(x), dim=1)
return x
Run Code Online (Sandbox Code Playgroud)
我的问题是:这是self.hidden什么?
它从返回nn.Linear。它可以x作为论据。到底是什么功能self.hidden?
谢谢
pytorch中nn.Linear的类定义是什么?
从文档:
CLASS torch.nn.Linear(in_features, out_features, bias=True)
对输入数据应用线性变换:y = xW ^ T + b
参数:
注意,线性方程中的权重W(形状(out_features,in_features))和偏差b(形状(out_features))是随机初始化的,以后可以更改(例如在训练网络时)。
让我们看一个具体的例子:
import torch
from torch import nn
m = nn.Linear(2, 1)
input = torch.tensor([[1.0, -1.0]])
output = m(input)
Run Code Online (Sandbox Code Playgroud)
参数随机初始化
>>> m.weight
tensor([[0.2683, 0.2599]])
>>> m.bias
tensor([0.6741])
Run Code Online (Sandbox Code Playgroud)
输出计算为 1.0 * 0.2683 - 1.0 * 0.2599 + 0.6741 = 0.6825
>>> print(output)
tensor([[0.6825]]
Run Code Online (Sandbox Code Playgroud)
在您的网络中,共有三层:具有784个节点的输入层,具有256个节点的一个隐藏层和具有10个节点的输出层。