如何像在keras中一样编写自己的"functional API"?

How to write your own "functional API" like in keras?

Keras 有一个函数式 API,您可以在函数调用后面输入信号,例如:

x = Input(shape=(782))
x = Dense(1024)(x)
x = Dense(1024)(x)

我想用相同的语法创建我自己的信号处理库,但我找不到任何东西(可能是因为我找不到这个方法的特殊词)。

所以假设一个简单的例子:

def add(w)(x):
    """
        w is the constant, x is the input signal
    """
    
    return w+x

x = np.random.randint(0,255,shape=(100,100,3))
x = add(5)(x)
x = add(5)(x)

我需要如何编写添加函数才能实现此行为?

您必须创建 类 并定义 built-in __call__ method in them. So eg. you would create an "Add" class where the constructor takes w argument, and also a __call__(x) method inside this class. Check the Dense layer implementation for more: https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/keras/layers/core.py#L1192

示例:

class Add:
    def __init__(self, w):
        self.w = w
    
    def __call__(self, x):
        return self.w + x

x = np.random.randint(0,255,size=(100,100,3))
x = Add(5)(x)
x = Add(5)(x)