why implementing the “call” method when subclassing a tf.keras layer(or model) class makes the layer(model) object callable?

穿精又带淫゛_ 提交于 2020-07-31 04:20:44

问题


When writing customized tf.keras layers, we have to implement the "call" method, since a object of a class can be called like a function with "()" only(?) if the object has a valid "__call__" method. while I didn't find something like

class tf.keras.model():
def __call__(self, input):
    return self.call(input)

in the keras.model source, how could all this work?


回答1:


from keras.models import Model
import inspect

inspect.getmro(Model)
# (keras.engine.training.Model, keras.engine.network.Network, keras.engine.layer._Layer)

inspect.getmro(CLS) returns a tuple of class CLS's base classes, including CLS, in method resolution order.

The __call__ method inside Model infact comes from keras.engine.layer._Layer class. You can refer the code here

On line 996, inside __call__ method call_fn is assigned as call & is indeed called on line 979.

So, essentially, in a way I guess, the following holds true -

def __call__(self, input):
    return self.call(input)

Let's discuss further!



来源:https://stackoverflow.com/questions/63008991/why-implementing-the-call-method-when-subclassing-a-tf-keras-layeror-model-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!