0% found this document useful (0 votes)
4 views6 pages

Practical 1

The document provides step-by-step instructions for implementing Convolutional Neural Networks (CNNs) using TensorFlow and Recurrent Neural Networks (RNNs) using PyTorch. It includes code examples for both models, utilizing the CIFAR-10 dataset for CNNs and the IMDB dataset for RNNs, along with instructions for running the code in VS Code. The document also covers necessary dependencies, data loading, model definition, training, evaluation, and plotting results.

Uploaded by

Tania Jamdar
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)
4 views6 pages

Practical 1

The document provides step-by-step instructions for implementing Convolutional Neural Networks (CNNs) using TensorFlow and Recurrent Neural Networks (RNNs) using PyTorch. It includes code examples for both models, utilizing the CIFAR-10 dataset for CNNs and the IMDB dataset for RNNs, along with instructions for running the code in VS Code. The document also covers necessary dependencies, data loading, model definition, training, evaluation, and plotting results.

Uploaded by

Tania Jamdar
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/ 6

Practical 1 :

Implementing advanced deep learning algorithms such as convolutional neural networks (CNNs) or
recurrent neural networks (RNNs) using Python libraries like TensorFlow or PyTorch.

step-by-step executable code for implementing Convolutional Neural Networks (CNNs) and
Recurrent Neural Networks (RNNs) using TensorFlow and PyTorch in Python. The examples use the
CIFAR-10 dataset (for CNN) and IMDB dataset (for RNN).

Step-by-Step Implementation for CNN (TensorFlow)

1. Install Dependencies:

bash

Copy code

pip install tensorflow matplotlib

2. Python Code for CNN (TensorFlow):

Save the following code in a file named cnn_tensorflow.py.

python

Copy code

import tensorflow as tf

from tensorflow.keras import layers, models

from tensorflow.keras.datasets import cifar10

import matplotlib.pyplot as plt

# Step 1: Load the CIFAR-10 dataset

(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Step 2: Normalize the data

x_train, x_test = x_train / 255.0, x_test / 255.0

# Step 3: One-hot encode the labels

y_train = tf.keras.utils.to_categorical(y_train, 10)

y_test = tf.keras.utils.to_categorical(y_test, 10)

# Step 4: Define the CNN model


model = models.Sequential([

layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),

layers.MaxPooling2D((2, 2)),

layers.Conv2D(64, (3, 3), activation='relu'),

layers.MaxPooling2D((2, 2)),

layers.Conv2D(64, (3, 3), activation='relu'),

layers.Flatten(),

layers.Dense(64, activation='relu'),

layers.Dense(10, activation='softmax')

])

# Step 5: Compile the model

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

# Step 6: Train the model

history = model.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))

# Step 7: Evaluate the model

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)

print(f"Test Accuracy: {test_acc}")

# Step 8: Plot training history

plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)

plt.plot(history.history['accuracy'], label='Train Accuracy')

plt.plot(history.history['val_accuracy'], label='Validation Accuracy')

plt.xlabel('Epoch')

plt.ylabel('Accuracy')

plt.legend()

plt.title('Model Accuracy')
plt.subplot(1, 2, 2)

plt.plot(history.history['loss'], label='Train Loss')

plt.plot(history.history['val_loss'], label='Validation Loss')

plt.xlabel('Epoch')

plt.ylabel('Loss')

plt.legend()

plt.title('Model Loss')

plt.show()

Step-by-Step Implementation for RNN (PyTorch)

1. Install Dependencies:

bash

Copy code

pip install torch torchvision torchtext matplotlib

2. Python Code for RNN (PyTorch):

Save the following code in a file named rnn_pytorch.py.

python

Copy code

import torch

import torch.nn as nn

import torch.optim as optim

from torchtext.datasets import IMDB

from torchtext.data.utils import get_tokenizer

from torchtext.vocab import build_vocab_from_iterator

from torch.utils.data import DataLoader

from torch.nn.utils.rnn import pad_sequence

import matplotlib.pyplot as plt

# Step 1: Load the IMDB dataset

train_iter, test_iter = IMDB()


# Step 2: Tokenize and build vocabulary

tokenizer = get_tokenizer('basic_english')

def yield_tokens(data_iter):

for _, text in data_iter:

yield tokenizer(text)

vocab = build_vocab_from_iterator(yield_tokens(train_iter), specials=["<unk>"])

vocab.set_default_index(vocab["<unk>"])

# Step 3: Prepare data loaders

def collate_batch(batch):

label_list, text_list = [], []

for label, text in batch:

label_list.append(0 if label == "neg" else 1)

text_list.append(torch.tensor(vocab(tokenizer(text)), dtype=torch.int64))

return torch.tensor(label_list, dtype=torch.int64), pad_sequence(text_list, batch_first=True)

train_dataloader = DataLoader(list(IMDB(split='train')), batch_size=8, shuffle=True,


collate_fn=collate_batch)

test_dataloader = DataLoader(list(IMDB(split='test')), batch_size=8, shuffle=False,


collate_fn=collate_batch)

# Step 4: Define the RNN model

class RNNModel(nn.Module):

def __init__(self, vocab_size, embed_dim, hidden_dim, output_dim):

super(RNNModel, self).__init__()

self.embedding = nn.Embedding(vocab_size, embed_dim)

self.rnn = nn.RNN(embed_dim, hidden_dim, batch_first=True)

self.fc = nn.Linear(hidden_dim, output_dim)

def forward(self, x):


embedded = self.embedding(x)

output, hidden = self.rnn(embedded)

return self.fc(hidden.squeeze(0))

model = RNNModel(len(vocab), 64, 128, 2)

# Step 5: Define loss and optimizer

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters(), lr=0.001)

# Step 6: Train the model

for epoch in range(5):

model.train()

total_loss = 0

for labels, texts in train_dataloader:

optimizer.zero_grad()

outputs = model(texts)

loss = criterion(outputs, labels)

loss.backward()

optimizer.step()

total_loss += loss.item()

print(f"Epoch {epoch+1}, Loss: {total_loss:.4f}")

# Step 7: Evaluate the model

correct = 0

total = 0

model.eval()

with torch.no_grad():

for labels, texts in test_dataloader:

outputs = model(texts)

predictions = outputs.argmax(1)
correct += (predictions == labels).sum().item()

total += labels.size(0)

print(f"Test Accuracy: {correct / total:.4f}")

Instructions to Run the Code in VS Code

1. Install Python extensions for VS Code if not already done.

2. Save each code block into separate .py files (cnn_tensorflow.py and rnn_pytorch.py).

3. Run the scripts in the terminal:

bash

Copy code

python cnn_tensorflow.py

python rnn_pytorch.py

You might also like