本文介绍了为什么实施“呼叫"?子类化tf.keras的layer(或模型)类时,该方法使layer(模型)对象可调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写自定义的tf.keras层时,我们必须实现"call"方法,因为类的对象可以像带有()"的函数一样被调用.如果对象具有有效的"__call__",则仅(?)方法.虽然我没有找到类似的东西

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)

在keras.model源代码中,所有这些工作如何工作?

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

推荐答案

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)按方法解析顺序返回类CLS的基类(包括CLS)的元组.

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

实际上,Model中的__call__方法来自keras.engine.layer._Layer类.您可以在此处

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

在线 996 中,在__call__方法call_fn中被分配为call&实际上是在 979 .

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)

让我们进一步讨论!

这篇关于为什么实施“呼叫"?子类化tf.keras的layer(或模型)类时,该方法使layer(模型)对象可调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:47