Keras序列到序列模型中的异常

时间:2019-02-07 00:54:56

标签: keras keras-layer keras-2 sequence-to-sequence

我正在尝试使用LSTM和密集神经网络在Keras中构建序列到序列模型。编码器对输入进行编码,然后将编码后的状态进行连接,然后将其输入到解码器中,该解码器是一个lstm +密集神经网络,可以及时输出分类标签。下面是我的代码的样子

from keras.utils import to_categorical
from keras.layers import Embedding, Bidirectional, GRU, Dense, TimeDistributed, LSTM, Input, Lambda
from keras.models import  Sequential, Model
import numpy as np
from keras import preprocessing
import keras

encoder_inputs_seq = Input(shape=(114,))
encoder_inputs = Embedding(input_dim= 1000 + 1, output_dim = 20)(encoder_inputs_seq)

x, state_h, state_c = LSTM(32, return_state=True)(encoder_inputs)
states = [state_h, state_c]

decoder_lstm = LSTM(32, return_sequences=True, return_state=True)
decoder_dense = Dense(9, activation='softmax')

all_outputs = []

input_state = keras.layers.RepeatVector(1)(state_h)


for i in range(5):
    # Run the decoder on one timestep
    new_input = keras.layers.concatenate([input_state, keras.layers.RepeatVector(1)(encoder_inputs[:, 1, :])], axis = -1)

    outputs, state_h, state_c = decoder_lstm(new_input,
                                             initial_state=states)
    outputs = decoder_dense(outputs)
    # Store the current prediction (we will concatenate all predictions later)
    all_outputs.append(outputs)
    # Reinject the outputs as inputs for the next loop iteration
    # as well as update the states
    states = [state_h, state_c]
    input_state = keras.layers.RepeatVector(1)(state_h)

decoder_outputs = Lambda(lambda x: keras.layers.concatenate(x, axis=1))(all_outputs)

model = Model(encoder_inputs_seq, decoder_outputs)

model.summary()

我遇到了以下例外情况

AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

我在哪里错了?

1 个答案:

答案 0 :(得分:0)

问题是您要切片张量(encoder_inputs[:, 1, :])而没有将其包装在Lambda层中。您在Keras模型中执行的每个操作都必须在一个层中。您可以通过以下方式将for循环内的第一行代码替换来解决此问题:

slice = Lambda(lambda x: x[:, 1, :])(encoder_inputs)
new_input = keras.layers.concatenate(
    [input_state, keras.layers.RepeatVector(1)(slice)], 
    axis = -1)