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

DL_5

The document outlines an assignment for performing sentiment analysis using a Recurrent Neural Network (RNN) with the IMDB dataset. It includes steps for training the RNN model, predicting sentiments on custom samples, and visualizing the results in a network graph. The code provided demonstrates the implementation of these tasks using Python libraries such as TensorFlow and NetworkX.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DL_5

The document outlines an assignment for performing sentiment analysis using a Recurrent Neural Network (RNN) with the IMDB dataset. It includes steps for training the RNN model, predicting sentiments on custom samples, and visualizing the results in a network graph. The code provided demonstrates the implementation of these tasks using Python libraries such as TensorFlow and NetworkX.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Assingmnet No.

: 5
Name: Gayatri Rajendra Jagadale
Roll No.:2447062
Batch: D
Problem Statement –
Perform Sentiment Analysis in the network graph using RNN.

A. Train RNN Model for Sentiment Analysis

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import imdb from tensorflow.keras.models import Seq
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense from tensorflow.ke
import pad_sequences

# Load IMDB dataset num_words = 10000


(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=num_words)

# Pad sequences maxlen = 100


x_train = pad_sequences(x_train, maxlen=maxlen) x_test = pad_sequences(x_test, max

# Build RNN model model = Sequential([


Embedding(num_words, 32, input_length=maxlen),
SimpleRNN(32),
Dense(1, activation='sigmoid')
])

D:\Users\shrey\anaconda3\lib\site-packages\keras\src\layers\core\ embedding.py:90:
`input_length` is deprecated.
Just remove it. warnings.warn(

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

Model: "sequential"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━
━━━━━━━━━━━━━━━━━┓

┃ Layer (type) ┃ Output Shape ┃


Param # ┃

┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━
━━━━━━━━━━━━━━━━━┩
│ embedding (Embedding) │ ? │
0 (unbuilt) │

├──────────────────────────────────────┼─────────────────────────────┼
─────────────────┤

│ simple_rnn (SimpleRNN) │ ? │
0 (unbuilt) │

├──────────────────────────────────────┼─────────────────────────────┼
─────────────────┤

│ dense (Dense) │ ? │
0 (unbuilt) │

└──────────────────────────────────────┴─────────────────────────────┴
─────────────────┘

Total params: 0 (0.00 B)


Trainable params: 0 (0.00 B)
Non-trainable params: 0 (0.00 B)
# Train model
model.fit(x_train, y_train, epochs=2, batch_size=64, validation_split=0.2)

Epoch 1/2 313/313 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - accuracy: 0.661


0.5950 - val_accuracy: 0.8330 - val_loss: 0.3964 Epoch 2/2 313/313 ━━━━━━━━━
- accuracy: 0.8688 - loss:
0.3197 - val_accuracy: 0.8386 - val_loss: 0.3749

<keras.src.callbacks.history.History at 0x1888798e100>
B. Predict Sentiments on Custom Samplessample_reviews = x_test[:10]
preds = (model.predict(sample_reviews) > 0.5).astype("int").flatten()

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 98ms/step

C. Visualize Sentiment in a Network Graph

# Decode function to get words


word_index = imdb.get_word_index()
index_word = {v+3: k for k, v in word_index.items()}
index_word[0] = '<PAD>' index_word[1] = '<START>'
index_word[2] = '<UNK>' index_word[3] = '<UNUSED>'

def decode_review(encoded_review): return '


'.join([index_word.get(i, '?') for i in encoded_review])
import networkx as nx

# Create a network graph


G = nx.Graph()

# Add nodes with sentiment for i, review in


enumerate(sample_reviews):
label = f"Review {i+1}\nSentiment: {'Positive' if preds[i] else
'Negative'}"
G.add_node(i, label=label, sentiment='positive' if preds[i] else
'negative')

# Connect similar sentiments for i


in range(len(preds)): for j in
range(i+1, len(preds)): if
preds[i] == preds[j]:
G.add_edge(i, j)

# Draw network
pos = nx.spring_layout(G, seed=42)
colors = ['green' if G.nodes[n]['sentiment'] == 'positive' else 'red'
for n in G.nodes()]
labels = nx.get_node_attributes(G, 'label')

plt.figure(figsize=(10, 7))
nx.draw(G, pos, ax=plt.gca(), with_labels=True, node_color=colors,
labels=labels,
font_size=8, node_size=1500)
plt.title("Sentiment Network Graph")
plt.show()

You might also like