Building an LSTM Neural Network for Binary Classification with TensorFlow


In this example we're using TensorFlow to build an LSTM neural network for a binary classification problem. We define the architecture of the LSTM model using the Sequential class from TensorFlow's Keras API. We add an LSTM layer with 64 units and a dense output layer with a sigmoid activation function.

Then we compile the model using the binary cross-entropy loss function, the Adam optimizer and accuracy as the evaluation metric. We then train the model on the training set using 10 epochs and a batch size of 32. Finally, we evaluate the performance of the model on the testing set and print the test loss and accuracy.

 1|  import tensorflow as tf
 2|  from tensorflow.keras.models import Sequential
 3|  from tensorflow.keras.layers import LSTM, Dense
 5|  # Define model architecture
 6|  model = Sequential()
 7|  model.add(LSTM(64, input_shape=(X_train.shape[1], X_train.shape[2])))
 8|  model.add(Dense(1, activation='sigmoid'))
10|  # Compile the model
11|  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
13|  # Train the model
14|  history =, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))
16|  # Evaluate the model
17|  loss, accuracy = model.evaluate(X_test, y_test)
18|  print(f'Test loss: {loss}, Test accuracy: {accuracy}')
Did you find this snippet useful?

Sign up for free to to add this to your code library