【问题标题】:Pytorch nn.Linear different output for same inputPytorch nn.Linear 相同输入的不同输出
【发布时间】:2021-09-09 04:19:45
【问题描述】:

出于学习目的,我正在尝试使用 pytorch 构建一个简单的感知器,它不应该被训练,而只是给出设定权重的输出。代码如下:

import torch.nn
from torch import tensor

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = torch.nn.Linear(3,1)
        self.relu = torch.nn.ReLU()
        # force weights to equal one
        with torch.no_grad():
            self.fc1.weight = torch.nn.Parameter(torch.ones_like(self.fc1.weight))

    def forward(self, x):
        x = self.fc1(x)
        output = self.relu(x)
        return output

net = Net()
test_tensor = tensor([1, 1, 1])
print(net(test_tensor.float()).item())

我希望这个单层神经网络输出 3。这大致(!)每次执行的输出,但范围从 2.5 到 3.5。随机性在哪里进入模型?

【问题讨论】:

    标签: python neural-network pytorch perceptron


    【解决方案1】:

    问:随机性在哪里进入模型?

    它来自bias init。正如你所看到的herebias 没有像你预期的那样初始化为零。

    你可以这样修复它:

    import torch
    from torch import nn
    
    class Net(torch.nn.Module):
        def __init__(self):
            super(Net, self).__init__()
            self.fc1 = torch.nn.Linear(3,1)
            self.relu = torch.nn.ReLU()
            # force weights to equal one
            with torch.no_grad():
                torch.nn.init.ones_(self.fc1.weight)
                torch.nn.init.zeros_(self.fc1.bias)
    
        def forward(self, x):
            x = self.fc1(x)
            output = self.relu(x)
            return output
    
    x = torch.tensor([1., 1., 1.])
    Net()(x)
    # >>> tensor([3.], grad_fn=<ReluBackward0>)
    

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2019-10-16
      相关资源
      最近更新 更多