为何喀拉拉邦会使用“致电"而不是__call__? [英] Why keras use "call" instead of __call__?

查看:62
本文介绍了为何喀拉拉邦会使用“致电"而不是__call__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在( https://www.tensorflow.org/tutorials/eager/custom_layers )

class MyDenseLayer(tf.keras.layers.Layer):
  def __init__(self, num_outputs):
    super(MyDenseLayer, self).__init__()
    self.num_outputs = num_outputs

  def build(self, input_shape):
    self.kernel = self.add_variable("kernel",
                                shape=[int(input_shape[-1]),
                                       self.num_outputs])

  def call(self, input):
    return tf.matmul(input, self.kernel)

最后两行是call方法,但它不像通常的python类方法 call 那样带有两个下划线.两者之间有什么区别吗?

The last two lines is call method, while it does not like usual python class method call with two underlines. Is any differences between those?

推荐答案

以下答案基于 https://tf.wiki/zh/basic/models.html .

基本上在Python中,当您使用ClassA()从类ClassA调用实例时,它等效于ClassA.__call__().因此在这种情况下使用__call__()代替call()似乎是合理的,对吧?

Basically in Python, when you call an instance from class ClassA using ClassA(), it is equivalent to ClassA.__call__(). So it seems reasonable to use __call__() instead of call() in this case, right?

但是,我们使用call()的原因是,当tf.keras调用模型或层时,它具有自己的内部操作,这些操作对于保持其内部结构必不可少.结果,它公开了用于重新加载客户的方法call(). __call()__调用call()以及一些内部操作,因此当我们重新加载从tf.keras.Modeltf.keras.Layer继承的call()时,我们可以调用客户代码,同时保留tf.keras的内部结构.

However, the reason we use call() is that when tf.keras calls a model or a layer, it has its own inner operations which are essential to keep its inner structure. As a result, it exposes a method call() for customer reload. __call()__ calls call() as well as some inner operations, so when we reload call() inheriting from tf.keras.Model or tf.keras.Layer, we can call our customer code while keeping tf.keras's inner structure.

例如,根据我的经验,如果您输入的是numpy数组而不是张量,那么如果您在call()中编写客户代码,则无需手动对其进行转换,但是如果覆盖__call__()由于未调用某些内部操作而成为一个问题.

For example, from my experience, if your input is a numpy array instead of a tensor, you don't need to transform it manually if you write customer code in call() but if you overwrite __call__(), it would be a problem since some inner operations are not called.

这篇关于为何喀拉拉邦会使用“致电"而不是__call__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆