代码之家  ›  专栏  ›  技术社区  ›  user697911

如何将参数传递到构造函数中?

  •  0
  • user697911  · 技术社区  · 7 年前

    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
    
            self.conv1 = nn.Conv2d(1,6,5)
            self.conv2 = nn.Conv2d(6, 16, 5)
            self.fc1 = nn.Linear(16*5*5, 120)
            self.fc2 = nn.Linear(120, 84)
            self.fc3 = nn.Linear(84, 10)
    
         def forward(self, x):
                x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))
                x = F.max_pool2d(F.relu(self.conv2(x)), 2)
                x = x.view(-1, self.num_flat_features(x))
                x = F.relu(self.fc1(x))
                x = F.relu(self.fc2(x))
                x = self.fc3(x)
    
                return x
    
        def num_flat_features(self, x):
            size = x.size()[1:]
            num_features = 1
            for s in size:
                num_features *= s
    
            return num_features
    
    net = Net()
    
    input = torch.randn(1,1,32,32)
    out = net(input)
    
    print(out)
    

    input = torch.randn(1,1,32,32)
    out = net(input)
    

    初始化时,我看不到如何使用“输入”进行初始化。

    2 回复  |  直到 7 年前
        1
  •  1
  •   stefan    7 年前
    net = Net()
    

    呼叫 __init__

    out = net(input)
    

    __call__ input 作为论据。 自从 Net nn.Module

    here nn.模块 还有 定义为 输入 作为参数。

        2
  •  0
  •   Gaurang Shah    7 年前

    Class 你在把一个论点传给我 object . 有区别。

    下面的示例显示了如何实现这一点。你需要实施 __call__ 方法

    class CallableClass:
        def __init__(self):
            pass
    
    
        def __call__(self, *args, **kwargs):
            print(args)
    
    
    class Net(CallableClass):
        def __init__(self):
            super(Net, self).__init__()
            pass
    
    net = Net()
    net(100)