【问题标题】:Clarification for self.forward function in PythonPython中self.forward函数的说明
【发布时间】:2021-04-02 17:28:02
【问题描述】:

我无法理解在 Loss 类下定义的 sample_losses = self.forward(output, y)

它从哪个“前向函数”获取输入作为前向函数是先前为所有三个类定义的,即Dense_layerActivation_ReLUActivation_Softmax

class Layer_Dense:
    def __init__(self, n_inputs, n_neurons):
        self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)
        self.biases = np.zeros((1, n_neurons))
        print(self.weights)
    def forward(self, inputs):
        self.output = np.dot(inputs, self.weights) + self.biases
class Activation_ReLU:
    def forward(self, inputs):
        self.output= np.maximum(0, inputs)
class Activation_Softmax:
    def forward (self, inputs):
        exp_values = np.exp(inputs - np.max(inputs, axis = 1, keepdims= True ))
        probabilities= exp_values/np.sum(exp_values, axis = 1, keepdims= True )
        self.output = probabilities
class Loss:
    def calculate(self, output, y):
        sample_losses = self.forward(output, y)
        data_loss = np.mean(sample_losses)
        return data_loss

【问题讨论】:

  • 它看起来不应该像那样。最有可能的是,那是一个完全不同的功能,有人弄错了名字。即使它是在它之前的其他类中定义的函数,该函数仍然会获得一个输入(除了“self”)
  • 请提供minimal reproducible example 说明如何使用此代码。目前这可能会引发一个异常,说“forward”属性不存在(这就是你想知道的原因)。
  • 这个网站对我帮助很大。我一直在想很多!我现在明白了。非常感谢您的支持

标签: python function class neural-network forward


【解决方案1】:

self.forward() 类似于 call 方法,但带有注册的钩子。这用于在调用实例名称时直接调用类中的方法。这些方法继承自 nn.Module。

https://gist.github.com/nathanhubens/5a9fc090dcfbf03759068ae0fc3df1c9

或者参考源码:

https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L485

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2013-12-23
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多