代码之家  ›  专栏  ›  技术社区  ›  Mehran

如何开发适用于任意大小输入的图层

  •  0
  • Mehran  · 技术社区  · 6 年前

    我正在尝试在Keras中开发一个可以使用3D张量的层。为了使它更灵活,我希望尽可能推迟依赖于输入的精确形状的代码。

    我的图层覆盖了5种方法:

    from tensorflow.python.keras.layers import Layer
    
    class MyLayer(Layer):
        def __init__(self, **kwargs):
            pass
    
        def build(self, input_shape):
            pass
    
        def call(self, inputs, verbose=False):
            second_dim = K.int_shape(inputs)[-2]
            # Do something with the second_dim
    
        def compute_output_shape(self, input_shape):
            pass
    
        def get_config(self):
            pass
    

    我使用的这一层是这样的:

    input = Input(batch_shape=(None, None, 128), name='input')
    x = MyLayer(name='my_layer')(input)
    model = Model(input, x)
    

    但我面临着一个错误,因为 second_dim None .我如何开发一个依赖于输入维度的层,但它由实际数据而不是输入层提供是可以的?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Mehran    6 年前

    最后我以不同的方式问了同一个问题,我得到了一个完美的答案:

    What is the right way to manipulate the shape of a tensor when there are unknown elements in it?

    要点是,不要直接处理尺寸。通过引用而不是价值来使用它们。所以,不要使用 K.int_shape 而是使用 K.shape .并使用Keras操作来合成和生成新形状:

    shape = K.shape(x)
    newShape = K.concatenate([
                                 shape[0:1], 
                                 shape[1:2] * shape[2:3],
                                 shape[3:4]
                             ])