具有自定义RNN Cell的keras双向层

时间:2017-12-20 04:57:03

标签: keras

以下型号

lstm_model = Sequential()
lstm_model.add(embedding)
tensor_lstm_cell = TensorLSTMCell(hidden_size=lstm_size, num_units=4)
lstm_model.add(Bidirectional(RNN(tensor_lstm_cell, return_sequences=True)))

抛出以下错误: ValueError: Unknown layer: TensorLSTMCell,它似乎来自config的双向加载。我想知道如何使用model.add功能将自定义rnn层添加到双向包装器

1 个答案:

答案 0 :(得分:3)

您可以使用CustomObjectScope打包Bidirectional行,以便它可以识别您的自定义对象TensorLSTMCell。例如,

from keras.utils.generic_utils import CustomObjectScope

class DummyLSTMCell(LSTMCell):
    pass

embedding = Embedding(10000, 32, input_shape=(None,))

lstm_model = Sequential()
lstm_model.add(embedding)
lstm_cell = DummyLSTMCell(32)
with CustomObjectScope({'DummyLSTMCell': DummyLSTMCell}):
    lstm_model.add(Bidirectional(RNN(lstm_cell, return_sequences=True)))