【问题标题】:How to apply a different dense layer for each timestep in Keras如何在 Keras 中为每个时间步应用不同的密集层
【发布时间】:2019-11-14 23:31:01
【问题描述】:

我知道应用 TimeDistributed(Dense) 在所有时间步上应用相同的密集层,但我想知道如何为每个时间步应用不同的密集层。时间步数不可变。

P.S.:我看过following link,似乎找不到答案

【问题讨论】:

    标签: keras neural-network recurrent-neural-network keras-layer gated-recurrent-unit


    【解决方案1】:

    您可以使用 LocallyConnected 层。

    LocallyConnected 层单词作为 Dense 层连接到每个kernel_size time_steps(在本例中为 1)。

    from tensorflow import keras
    from tensorflow.keras.layers import *
    from tensorflow.keras.models import Model
    
    sequence_length = 10
    n_features = 4
    
    def make_model():
      inp = Input((sequence_length, n_features))
      h1 = LocallyConnected1D(8, 1, 1)(inp)
      out = Flatten()(h1)
      model = Model(inp, out)
      model.compile('adam', 'mse')
      return model
    
    model = make_model()
    model.summary()
    

    总而言之,LocallyConnected 层使用的变量数量为 (output_dims * (input_dims + bias)) * time_steps 或 (8 * (4 + 1)) * 10 = 400。

    换一种说法:上面的本地连接层表现为 10 个不同的 Dense 层,每个层都连接到其时间步长(因为我们选择 kernel_size 为 1)。这些由 50 个变量组成的块中的每一个都是一个形状为 (input_dims, output_dims) 的权重矩阵加上一个大小为 (output_dims) 的偏置向量。

    另请注意,如果 input_shape 为 (sequence_len, n_features),Dense(output_dims)Conv1D(output_dims, 1, 1) 是等价的。

    即这个模型:

    def make_model():
      inp = Input((sequence_length, n_features))
      h1 = Conv1D(8, 1, 1)(inp)
      out = Flatten()(h1)
      model = Model(inp, out)
    

    还有这个模型:

    def make_model():
      inp = Input((sequence_length, n_features))
      h1 = Dense(8)(inp)
      out = Flatten()(h1)
      model = Model(inp, out)
    

    都是一样的。

    【讨论】:

    • 感谢您的澄清!
    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多