【问题标题】:Keras Dense layer gets input_shape wrongKeras Dense 层的 input_shape 错误
【发布时间】:2018-07-24 06:48:49
【问题描述】:

我编写了下面的自定义层,然后当我尝试添加 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) 但下一行失败。

【问题讨论】:

    标签: tensorflow keras keras-layer


    【解决方案1】:

    添加 compute_output_shape 函数即可解决问题。

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2018-06-16
      • 2019-02-04
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多