Search code examples
pythonneural-networkkeraslstm

How to use output of Neural Network as input for another NN in Keras


I implemented an LSTM with Keras and trained it on a corpus. Now I want to take the output of the NN and pass it as input to another NN model and test on a test set. I saved the model of the NN, but I do not know how to extract the output and feed it to the other NN. How can I do it?

This is my code:

model = Sequential()
model.add(Embedding(vocab_size, 50, input_length=seq_length))
model.add(LSTM(100, return_sequences=True))
model.add(LSTM(100))
model.add(Dense(100, activation='relu'))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())
# compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])
# fit model
model.fit(X, y, batch_size=128, epochs=500)
# save the model to file
model.save('model.h5')

Solution

  • There isn't any need to save a model to extract output . You can simply use the predict()function to get your output. In your case to get the output from your model pass the test input as shown

    prediction = model.predict(X_test)
    

    where X_test is your test input and 'prediction' will contain your output which can then be printed.

    For giving this output as input to another model , first create another model like you have one and then pass the prediction variable into the model.fit() function.