TheM00s3
TheM00s3

Reputation: 3711

keras bidirectional layer with custom RNN Cell

The following model

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)))

throws the following error: ValueError: Unknown layer: TensorLSTMCell, it seems to come from the bidirectional loading it from config. Im wondering how can I use the model.add functionality to add a custom rnn layer to the bidirectional wrapper

Upvotes: 3

Views: 877

Answers (1)

Yu-Yang
Yu-Yang

Reputation: 14619

You can use CustomObjectScope to wrap the Bidirectional line so that it can recognize your custom object TensorLSTMCell. For example,

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)))

Upvotes: 4

Related Questions