pytorch中nn.Linear的类定义是什么

2024-04-19 03:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有火把的密码

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

我的问题:这是什么self.hidden

它从nn.Linear返回。它可以把x作为参数。self.hidden的具体功能是什么?

谢谢


Tags: importself密码outputinitdefasnn
2条回答

what is the class definition of nn.Linear in pytorch?

来自documentation


CLASS torch.nn.Linear(in_features, out_features, bias=True)

对传入数据应用线性转换:y=xW^T+b

参数:

  • in_features每个输入样本的大小
  • 输出特性–每个输出样本的大小
  • 偏差–如果设置为False,则层将不会学习相加偏差。默认值:True

请注意,线性方程中的权重W(形状(外特征,内特征)和偏移b(形状(外特征))是随机初始化的,并且可以稍后更改(例如,在网络训练期间)。

让我们看一个具体的例子:

import torch
from torch import nn

m = nn.Linear(2, 1)
input = torch.tensor([[1.0, -1.0]])  
output = m(input)

参数是随机初始化的

>>> m.weight
tensor([[0.2683, 0.2599]])
>>> m.bias
tensor([0.6741])

输出计算为1.0 * 0.2683 - 1.0 * 0.2599 + 0.6741 = 0.6825

>>> print(output)
tensor([[0.6825]]

在您的网络中,有三层:784个节点的输入层、256个节点的一个隐藏层和10个节点的输出层。

定义为具有两个层的Network,即隐藏层和输出层。 粗略地说,隐藏层的功能是保存训练期间可以优化的参数。

相关问题 更多 >