我一直在使用Keras框架进行递归神经网络实现,并且在构建模型时遇到了一些问题。
Keras 2.2.4
Tensorflow 1.14.0
我的模型仅包含三层:嵌入,递归和密集层。当前看起来像这样:
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim= EMBEDDING_DIM, input_length= W_SIZE))
if MODEL == 'GRU':
model.add(CuDNNGRU(NUM_UNITS))
if MODEL == 'RNN':
model.add(SimpleRNN(NUM_UNITS))
if MODEL == 'LSTM':
model.add(CuDNNLSTM(NUM_UNITS))
model.add(Dense(vocab_size, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
我要执行的操作是将return_state=True
添加到循环图层中,以便在使用model.predict()
函数时获得这些状态,但是当我添加它时,得到以下内容错误:
TypeError: All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.
我尝试在Dense层周围使用TimeDistributed包装器层,但是它没有任何改变。
谢谢!
答案 0 :(得分:1)
顺序API专为直链模型而设计,就像链一样。也就是说,一层的输出连接到下一层,依此类推。
因此,如果要输出多个输出,则需要Keras Functional API。
from tensorflow.keras import layers, models
inp = layers.Input(shape=(n_timesteps,))
out = layers.Embedding(input_dim=vocab_size, output_dim= EMBEDDING_DIM, input_length= n_timesteps)(inp)
if MODEL == 'GRU':
out, state = layers.CuDNNGRU(NUM_UNITS, return_state=True)(out)
if MODEL == 'RNN':
out, state = layers.SimpleRNN(NUM_UNITS, return_state=True)(out)
if MODEL == 'LSTM':
out, state = layers.CuDNNLSTM(NUM_UNITS, return_state=True)(out)
out = layers.Dense(vocab_size, activation='softmax')(out)
model = models.Model(inputs=inp, outputs=[out, state])
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
model.summary()