我一直在使用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.我尝试过在密集层周围使用TimeDistributed包装层,但是它没有改变任何东西。
提前感谢!
发布于 2019-11-25 20:40:37
顺序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()https://stackoverflow.com/questions/59036215
复制相似问题