import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
import matplotlib.pyplot as plt

# Load IMDB dataset
num_words = 10000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=num_words)

# Pad sequences
maxlen = 200
x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)

# Build LSTM model
model = Sequential([
    Embedding(num_words, 128, input_length=maxlen),
    LSTM(128, dropout=0.2, recurrent_dropout=0.2),
    Dense(1, activation='sigmoid')
])

# Compile & Train
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=3, batch_size=64, validation_data=(x_test, y_test))

# Evaluate
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test Accuracy:", test_acc)

# Plot accuracy & loss
epochs = range(1, len(history.history['accuracy'])+1)
plt.subplot(1,2,1)
plt.plot(epochs, history.history['accuracy'], 'b', label='Train')
plt.plot(epochs, history.history['val_accuracy'], 'r', label='Test')
plt.title('Accuracy'); plt.legend()

plt.subplot(1,2,2)
plt.plot(epochs, history.history['loss'], 'b', label='Train')
plt.plot(epochs, history.history['val_loss'], 'r', label='Test')
plt.title('Loss'); plt.legend()
plt.show()