我写了下面的自定义层,当我尝试在之后添加一个Dense层时,它得到了input_shape错误,并期望该层之前的张量的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),但下一行失败。
答案 0 :(得分:0)
添加compute_output_shape函数可以解决该问题。
def compute_output_shape(self, input_shape):
return (input_shape[0], self.feature_dim)
任何修改形状的图层都必须具有compute_output_shape。