初始化并访问自定义keras层中的一系列权重



我正在编写一个自定义的keras层,用于在傅立叶域中的CNN体系结构中进行卷积:

class Fourier_Conv2D(Layer):
def __init__(self, no_of_kernels, **kwargs):
    self.no_of_kernels = no_of_kernels
    super(Fourier_Conv2D, self).__init__(**kwargs)
def build(self, input_shape):
    self.kernel = self.add_weight(name = 'kernel', 
                                  shape = input_shape + (self.no_of_kernels,), 
                                  initializer = 'uniform', trainable = True)
    super(Fourier_Conv2D, self).build(input_shape)
def call(self, x):
    return K.dot(x, self.kernel[0]) 

在呼叫函数中,我需要使用每个内核的FFT(根据卷积定理)进行输入FFT的点数乘法,然后在将此总和传递给激活函数之前添加产物。但是,如何在呼叫函数中分别访问每个权重,因为使用数组索引执行以下属性错误 -

AttributeError                            Traceback (most recent call last)
<ipython-input-71-9617a8e7ab2e> in <module>()
      1 x = Fourier_Conv2D(5)
----> 2 x.call((2,2,1))
<ipython-input-70-02ded53b8f6f> in call(self, x)
     11 
     12     def call(self, x):
---> 13         return K.dot(x, self.kernel[0])
     14 
AttributeError: 'Fourier_Conv2D' object has no attribute 'kernel'

事先感谢您解决错误的任何帮助。

您无法正确使用图层。线x.call((2,2,1))没有道理,因为您需要将张量传递到该层。您应该做这样的事情:

x = Input((3,4))
custom_layer = Fourier_Conv2D(10)
output = custom_layer(x)

此外,您的图层的定义有一些错误。以下应有效:

class Fourier_Conv2D(Layer):
    def __init__(self, no_of_kernels, **kwargs):
        self.no_of_kernels = no_of_kernels
        super(Fourier_Conv2D, self).__init__(**kwargs)
    def build(self, input_shape):
        # Note the changes to the shape parameter
        self.kernel = self.add_weight(name = 'kernel', 
                                      shape = (int(input_shape[-1]), self.no_of_kernels), 
                                      initializer = 'uniform', trainable = True)
        super(Fourier_Conv2D, self).build(input_shape)
    def call(self, x):
        return K.dot(x, self.kernel) # kernel[0] --> kernel

最新更新