Keras的遮罩层作为LSTM层的输入

4

我正在尝试创建一个LSTM模型。在将数据传递到第一个LSTM层之前,我想添加一个Masking层。我能够使用Keras中的Sequential方法来实现这一点。请参见示例。然而,当我尝试以不同的方式编写代码时,我会得到一个值错误(见下文)。有什么想法如何解决这个问题吗?

import keras


def network_structure(window_len, n_features, lstm_neurons):

    masking = keras.layers.Masking(

        mask_value=0.0, input_shape=(window_len, n_features)

    )

    lstm_h1 = keras.layers.LSTM(lstm_neurons)(masking)

    lstm_h2 = keras.layers.LSTM(lstm_neurons)(lstm_h1)

    cte = keras.layers.Dense(
        1,
        activation='linear',
        name='CTE',
    )(lstm_h2)

    ate = keras.layers.Dense(
        1,
        activation='linear',
        name='ATE',
    )(lstm_h2)

    pae = keras.layers.Dense(
        1,
        activation='linear',
        name='PAE',
    )(lstm_h2)

    model = keras.models.Model(
        inputs=masking,
        outputs=[cte, ate, pae]
    )

    model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae'])

    model.summary()

    return model


model = network_structure(32, 44, 125)   

错误信息:

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Python35\lib\site-packages\keras\engine\topology.py", line 442, in assert_input_compatibility
    K.is_keras_tensor(x)
  File "C:\Python35\lib\site-packages\keras\backend\tensorflow_backend.py", line 468, in is_keras_tensor
    raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.core.Masking'>`. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Master Tk/PycharmProjects/FPL/testcompile.py", line 46, in <module>
    model = network_structure(32, 44, 125)
  File "C:/Users/Master Tk/PycharmProjects/FPL/testcompile.py", line 12, in network_structure
    lstm_h1 = keras.layers.LSTM(lstm_neurons)(masking)
  File "C:\Python35\lib\site-packages\keras\layers\recurrent.py", line 499, in __call__
    return super(RNN, self).__call__(inputs, **kwargs)
  File "C:\Python35\lib\site-packages\keras\engine\topology.py", line 575, in __call__
    self.assert_input_compatibility(inputs)
  File "C:\Python35\lib\site-packages\keras\engine\topology.py", line 448, in assert_input_compatibility
    str(inputs) + '. All inputs to the layer '
ValueError: Layer lstm_1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.core.Masking'>. Full input: [<keras.layers.core.Masking object at 0x000002224683A780>]. All inputs to the layer should be tensors.
1个回答

4

您忘记创建输入层了。首先定义输入层,然后将占位符张量传递给Masking层:

inp = Input(shape=(window_len, n_features))
masking = keras.layers.Masking(mask_value=0.0)(inp)
lstm_h1 = keras.layers.LSTM(lstm_neurons)(masking)

同时不要忘记通过将输入张量作为inputs参数传递来相应地更改模型定义:

model = keras.models.Model(inputs=inp, outputs=[cte, ate, pae])

如果我们必须使用双向LSTM而不是传统的LSTM,该方法会如何改变? - clanofsol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接