如何使pool2d层的windowsize可训练?

时间:2019-07-15 01:37:45

标签: tensorflow keras neural-network deep-learning

我正在尝试使用keras构建自定义图层。它包括两个池化层。我希望使这两层的window_size易于训练。但是我不知道该怎么做。

class SauvolaLayer(Layer):
    def __init__(self, 
                 window_size=15,
                 init_k=0.2,
                 init_R=0.5,
                 train_k=False,
                 train_R=False,
                 train_W=False,
                 **kwargs):
        self.window_size = window_size
        self.init_k = init_k
        self.init_R = init_R
        self.init_W = window_size
        self.train_k = train_k
        self.train_R = train_R
        self.train_W = train_W
        super(SauvolaLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # 为该层创建一个可训练的权重
        self.k = self.add_weight(name='SauvolaLayer_k',
                                shape=(1,1,1,1),
                                dtype='float32',
                                initializer=constant(self.init_k),
                                trainable=self.train_k,
                                constraint=NonNeg(),
                                )
        self.R = self.add_weight(name='SauvolaLayer_R',
                                shape=(1,1,1,1),
                                dtype='float32',
                                initializer=constant(self.init_R),
                                trainable=self.train_R,
                                constraint=NonNeg(),
                                )
        self.window_size = self.add_weight(name='SauvolaLayer_window_size',
                                shape=(1),
                                dtype='float32',
                                initializer=constant(self.init_W),
                                trainable=self.train_W,
                                constraint=NonNeg(),
                                )
        super(SauvolaLayer, self).build(input_shape)  # 一定要在最后调用它

    def call(self, x):
        r = K.cast(self.R,'float64')
        x = K.cast(x, 'float64')
        window_size = K.cast(self.window_size, 'uint64')

        avg_x = K.pool2d(x,
                        pool_size=(window_size,window_size),
                        strides=(1,1),
                        padding='same',
                        data_format='channels_last',
                        pool_mode='avg')
        x2_avg = K.pool2d(x**2,
                        pool_size=(window_size,window_size),
                        strides=(1,1),
                        padding='same',
                        data_format='channels_last',
                        pool_mode='avg')
        dev_x = K.sqrt(K.clip(x2_avg - avg_x**2,0,255))
        T = avg_x *(1. + K.cast(self.k,'float64')*(dev_x/r)-1.)
        T = K.cast(T, 'float32')
        return T

    def compute_output_shape(self, input_shape):
        return input_shape    

它表示错误:

TypeError: 'int' object is not iterable

0 个答案:

没有答案