0% found this document useful (0 votes)
6 views

Ex NO 9 DL LAB

The document outlines a procedure for performing sentiment analysis on IMDb movie reviews using a Recurrent Neural Network (RNN). It includes steps for data preprocessing, model building, training, evaluation, and visualization of results. The provided code demonstrates the implementation of these steps using TensorFlow and Keras.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Ex NO 9 DL LAB

The document outlines a procedure for performing sentiment analysis on IMDb movie reviews using a Recurrent Neural Network (RNN). It includes steps for data preprocessing, model building, training, evaluation, and visualization of results. The provided code demonstrates the implementation of these steps using TensorFlow and Keras.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Ex. No.

9: Perform Sentiment Analysis using RNN


Aim:

To perform sentiment analysis on IMDb movie reviews using a Recurrent Neural Network
(RNN) model.

Procedure:

1. Load the IMDb movie reviews dataset and preprocess the text data.
2. Use an Embedding layer to convert input sequences into dense vectors of fixed size.
3. Add a SimpleRNN layer to process the embedded sequences.
4. Add a Dense layer with a sigmoid activation function for binary sentiment classification.
5. Compile the model using the Adam optimizer and binary crossentropy loss.
6. Use a TensorBoard callback to log metrics during training.
7. Train the model on the IMDb dataset.
8. Evaluate the model on the test set and print the accuracy.
9. Save the trained model for later use.
10. Plot the training and validation accuracy over epochs.

CODE:

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, SimpleRNN, Dense
from tensorflow.keras.callbacks import TensorBoard
import datetime
import matplotlib.pyplot as plt

# Load and preprocess the IMDb movie reviews dataset


max_features = 10000 # Number of words to consider as features
max_len = 200 # Maximum length of a sequence
(x_train, y_train), (x_test, y_test) =
imdb.load_data(num_words=max_features)
x_train = pad_sequences(x_train, maxlen=max_len)
x_test = pad_sequences(x_test, maxlen=max_len)

# Build the RNN model


model = Sequential()
model.add(Embedding(input_dim=max_features, output_dim=32,
input_length=max_len))
model.add(SimpleRNN(units=32))
model.add(Dense(units=1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])

# Create a summary writer


log_dir = "logs/sentiment_analysis_rnn/" +
datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)

# Train the model


epochs = 5
history = model.fit(
x_train, y_train,
epochs=epochs,
batch_size=64,
validation_split=0.2,
callbacks=[tensorboard_callback]
)

# Evaluate the model on the test set


test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_acc}')

# Save the model


model.save('sentiment_analysis_rnn_model.h5')

# Plot training history


plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
OUTPUT

You might also like