Keras 密集层出错 input_shape

Keras Dense layer gets input_shape wrong

我写了下面的自定义层,然后当我尝试添加一个 Dense 层时,它得到了 input_shape 错误,并期望层之前张量的形状 [-1] 维度。

from keras import backend as K
from keras.engine.topology import Layer
from keras.layers import Conv2D, Dense, Input


class SMSO(Layer):
    def __init__(self, feature_dim=256, **kwargs):
        self.feature_dim = feature_dim
        super(SMSO, self).__init__(**kwargs)

    def build(self, input_shape):
        self.scale = self.add_weight('scale',
                                     shape=(1, self.feature_dim),
                                     initializer='ones',
                                     trainable=True)
        self.offset = self.add_weight('offset',
                                      shape=(1, self.feature_dim),
                                      initializer='zeros',
                                      trainable=True)
        super(SMSO, self).build(input_shape)

    def call(self, x):
        x = x - K.mean(x, axis=(1, 2), keepdims=True)
        x = K.square(Conv2D(self.feature_dim, 1)(x))
        x = K.sqrt(K.sum(x, axis=(1, 2)))
        return self.scale * x + self.offset

x = Input(shape=(10, 10, 32))
l1 = SMSO(16)(x)
print(l1.shape)
l2 = Dense(10)(l1)

这是重现错误的代码。 l1.shape 按预期给出 (?, 16) 但下一行失败。

添加一个compute_output_shape函数解决问题。

def compute_output_shape(self, input_shape):
    return (input_shape[0], self.feature_dim)

任何修改形状的层都需要有一个compute_output_shape。