RLDL File
RLDL File
RLDL File
1. Download Spyder: Go to the Spyder IDE website (Click here) and find the download section.
Click on the link to download the Windows installer (.exe file).
1
2. Run the Installer: Once the download is complete, locate the downloaded file (usually in your
Downloads folder) and double-click on it to run the installer.
3. Follow Installation Wizard: The installer will guide you through the installation process. Click
"I agree" and "Next" to proceed through the setup steps.
2
4. Choose Installation Location: You'll be asked to choose where to install Spyder. You can stick with
the default location or choose another directory. Click "INSTALL" to continue. The installer will copy the
necessary files to your computer.
3
5. Complete Installation: Once the installation is complete, you'll see a confirmation message. Click
"Finish" to exit the installer.
Program
A=3
B=5
C=a+b
print ("The sum of a and b is", c)
Output
4
Practical – 2
1. Installing Keras, Tensorflow and Pytorch libraries and making use of them.
3. Write the below commands and click on Run cell to install below libraries if not installed
previously.
5
A) Program using Keras
from keras.models import Sequential
from keras.layers import Dense
# Generate synthetic data
import numpy as np
X_train = np.random.rand(1000, 5) # 1000 samples, each with 5 features
y_train = np.random.randint(0, 2, 1000) # 1000 binary labels (0 or 1)
# Define a simple neural network model
model = Sequential([
Dense(16, activation='relu', input_shape=(5,)), # Hidden layer with 16 neurons
Dense(8, activation='relu'), # Hidden layer with 8 neurons
Dense(1, activation='sigmoid') # Output layer with 1 neuron for binary
classification
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5, batch_size=32)
# Evaluate the model
loss, accuracy = model.evaluate(X_train, y_train)
print(f"Model Loss: {loss}")
print(f"Model Accuracy: {accuracy}")
OUTPUT
6
B) Program using Tensorflow
import tensorflow as tf
import numpy as np
# Generate synthetic data for linear regression: y = 3x + 2 + noise
X_train = np.linspace(0, 10, 100)
y_train = 3 * X_train + 2 + np.random.randn(*X_train.shape) * 0.5
# Define the model: a simple linear regression
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, input_shape=(1,))
])
# Compile the model
model.compile(optimizer='sgd', loss='mse')
# Train the model
model.fit(X_train, y_train, epochs=10, batch_size=10)
# Predict using the model
y_pred = model.predict(X_train)
# Evaluate the model
loss = model.evaluate(X_train, y_train)
print(f"Final Loss: {loss}")
# Display first 5 predictions
for i in range(5):
print(f"Input: {X_train[i]}, True Output: {y_train[i]}, Predicted Output: {y_pred[i][0]}")
OUTPUT
7
A) Program using Pytorch
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# Generate synthetic data for linear regression: y = 3x + 2 + noise
X_train = np.linspace(0, 10, 100).reshape(-1, 1) # 100 samples, each with 1 feature
y_train = 3 * X_train + 2 + np.random.randn(*X_train.shape) * 0.5
# Convert numpy arrays to PyTorch tensors
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
# Define the model: a simple linear regression
class LinearRegressionModel(nn.Module):
def init (self):
super(LinearRegressionModel, self). init ()
self.linear = nn.Linear(1, 1) # One input feature and one output feature
def forward(self, x):
return self.linear(x)
model = LinearRegressionModel()
# Verify that the model parameters are registered
print("Model parameters:")
for param in model.parameters():
print(param)
# Define the loss function and optimizer
criterion = nn.MSELoss() # Mean Squared Error loss
optimizer = optim.SGD(model.parameters(), lr=0.01) # Stochastic Gradient Descent optimizer
# Train the model
num_epochs = 10
for epoch in range(num_epochs):
# Forward pass
outputs = model(X_train)
loss = criterion(outputs, y_train)
# Backward pass and optimization
optimizer.zero_grad() # Clear previous gradients
loss.backward() # Compute gradients
optimizer.step() # Update model parameters
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# Predict using the model
with torch.no_grad():
y_pred = model(X_train)
# Print the final loss
8
print(f'Final Loss: {loss.item():.4f}') # Display first 5 predictions
for i in range(5):
print(f"Input: {X_train[i].item()}, True Output: {y_train[i].item()}, Predicted Output:
{y_pred[i].item()}")
OUTPUT
9
Practical-3
3. Implement Q-learning with pure Python to play a game
Environment set up and intro to OpenAl Gym
Write Q-learning algorithm and train agent to play game
Watch trained agent play game
CODE
import gym
import numpy as np
# Q-learning algorithm
for episode in range(episodes):
state = env.reset()[0] # Get the initial state
done = False
total_reward = 0
10
while not done:
# Choose action
if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample()
# Explore action space
else:
# Ensure Q-values exist for the state- action pair
action = np.argmax([get_q_value(state, a) for a in range(env.action_space.n)])
# Exploit learned values
# Take action
observation, reward, terminated, truncated, info = env.step(action)
new_state = observation
done = terminated or truncated
# Update Q-value
old_value = get_q_value(state, action)
next_max = np.max([get_q_value(new_state, a)
for a in range(env.action_space.n)])
new_value = old_value + alpha * (reward + gamma * next_max - old_value)
set_q_value(state, action, new_value)
state = new_state
total_reward += reward
# Update epsilon
epsilon = max(min_epsilon, epsilon * epsilon_decay)
if episode % 100 == 0:
print(f"Episode {episode}: Total
reward = {total_reward}, Epsilon = {epsilon}")
# Test the agent after training
state = env.reset()[0] # Get the initial state
done = False
total_reward = 0
11
OUTPUT
12
Practical – 4
4. Implement deep Q-network with PyTorch
CODE
import torch
import torch.nn as nn
import torch.optim as optim
import gym
import numpy as np
from collections import namedtuple, deque
import random
class ReplayBuffer:
def init (self, capacity):
self.buffer = deque(maxlen=capacity)
# Hyperparameters
gamma = 0.99 # Discount factor
epsilon = 0.1 # Exploration rate
alpha = 0.001 # Learning rate
13
batch_size = 64 # Batch size for sampling from replay buffer
buffer_capacity = 10000
num_episodes = 1000
# Initialize environment
env = gym.make('FrozenLake-v1', is_slippery=True, render_mode='human')
for i in range(batch_size):
state, next_state = batch.state[i], batch.next_state[i]
if isinstance(state, tuple):
state = state[0]
if isinstance(next_state, tuple):
14
next_state = next_state[0]
states[i, state] = 1.0
next_states[i, next_state] = 1.0
# Training loop
for episode in range(num_episodes):
state = env.reset()[0]
done = False
total_reward = 0
# Print progress
if episode % 100 == 0:
print(f"Episode {episode}: Total reward = {total_reward}")
OUTPUT
16
Practical – 5
import numpy as np
i, j = state
if action == 'up':
next_state = (max(0, i - 1), j)
elif action == 'down':
next_state = (min(self.rows - 1, i + 1), j)
elif action == 'left':
next_state = (i, max(0, j - 1))
elif action == 'right':
next_state = (i, min(self.cols - 1, j + 1))
return next_state
while True:
delta = 0
for state in self.states:
if state in self.terminal_states:
continue
17
v = V[state]
action = self.policy[state]
next_state = self.get_next_state(state, action)
V[state] = self.get_reward(state) + self.gamma * V[next_state]
return V
old_action = self.policy[state]
action_values = []
best_action = self.actions[np.argmax(action_values)]
self.policy[state] = best_action
if best_action != old_action:
policy_stable = False
return policy_stable
def policy_iteration(self):
while True:
V = self.policy_evaluation()
policy_stable = self.policy_improvement(V)
if policy_stable:
break
return self.policy, V
# Example usage
if _name_ == "_main_":
# Define the grid world environment
rewards = {
(0, 3): 1,
18
(1, 3): -1
}
terminal_states = [(0, 3), (1, 3)]
grid_world = GridWorld(3, 4, start_state=(2, 0), terminal_states=terminal_states,
rewards=rewards)
print("Optimal Policy:")
for i in range(grid_world.rows):
for j in range(grid_world.cols):
if (i, j) in terminal_states:
print(" T ", end=" ")
else:
print(f" {optimal_policy[(i, j)][0].upper()} ", end=" ")
print()
OUTPUT
19
Practical – 6
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, Embedding, Bidirectional
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
vocab_size = len(tokenizer.word_index) + 1
question_sequences = tokenizer.texts_to_sequences(questions)
answer_sequences = tokenizer.texts_to_sequences(answers)
# Model architecture
embedding_dim = 100
latent_dim = 128
# Encoder
encoder_inputs = Input(shape=(None,))
encoder_embedding = Embedding(vocab_size, embedding_dim)(encoder_inputs)
encoder_bi_lstm = Bidirectional(LSTM(latent_dim, return_state=True))
20
_, forward_h, forward_c, backward_h, backward_c = encoder_bi_lstm(encoder_embedding)
state_h = tf.keras.layers.Concatenate()([forward_h, backward_h])
state_c = tf.keras.layers.Concatenate()([forward_c, backward_c])
# Decoder
decoder_inputs = Input(shape=(None,))
decoder_embedding = Embedding(vocab_size, embedding_dim)(decoder_inputs)
decoder_lstm = LSTM(latent_dim * 2, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_embedding, initial_state=encoder_states)
decoder_dense = Dense(vocab_size, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Compile model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy')
# Train model
model.fit([question_padded, answer_padded], np.expand_dims(answer_padded, -1),
batch_size=16, epochs=100, validation_split=0.2)
# Inference setup
encoder_model = Model(encoder_inputs, encoder_states)
decoder_model = Model(
[decoder_inputs] + decoder_states_inputs,
[decoder_outputs] + decoder_states)
# Response generation
def decode_sequence(input_seq):
states_value = encoder_model.predict(input_seq)
states_value = [h, c]
return decoded_sentence
# Example conversation
print(respond("Hi"))
print(respond("What is your name?"))
OUTPUT
22
Practical – 7
7. Image classification on MNIST dataset(CNN model with fully connected
layer)
CODE
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten
from keras import backend as k
(x_train, y_train), (x_test, y_test) = mnist.load_data()
img_rows, img_cols=28, 28
if k.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
inpx = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
inpx = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
inpx = Input(shape=inpx)
layer1 = Conv2D(32, kernel_size=(3, 3), activation='relu')(inpx)
layer2 = Conv2D(64, (3, 3), activation='relu')(layer1)
layer3 = MaxPooling2D(pool_size=(3, 3))(layer2)
layer4 = Dropout(0.5)(layer3)
layer5 = Flatten()(layer4)ss
layer6 = Dense(250, activation='sigmoid')(layer5)
layer7 = Dense(10, activation='softmax')(layer6)
model = Model([inpx], layer7)
model.compile(optimizer=keras.optimizers.Adadelta(),
loss=keras.losses.categorical_crossentropy,
metrics=['accuracy'])
24
Practical – 8
8. Train a sentiment analysis model on IMDB dataset, use RNN layers with
LSTM/GRU
CODE
word_idx = imdb.get_word_index()
word_idx = {i: word for word, i in word_idx.items()}
print([word_idx[i] for i in x_train[0]])
activation='tanh',
return_sequences=False))
25
RNN_model.add(Dense(1, activation='sigmoid'))
# printing model summary
print(RNN_model.summary())
# Compiling model
RNN_model.compile( loss="binary_crossentropy",
optimizer='adam',
metrics=['accuracy']
)
Output:
26
Gated Recurrent Units (GRU)
print()
print("GRU model Score---> ", gru_model.evaluate(x_test, y_test, verbose=0))
Output
27
Practical – 9
9. Applying Deep Learning Models in Natural Language Processing (NLP)
Theory
Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on the
interaction between computers and human languages. It involves developing algorithms and models
that enable machines to understand, interpret, and generate human language.
Deep Learning in NLP: Deep learning has revolutionized NLP by providing powerful models that
can learn complex patterns and representations from large amounts of text data. Key deep learning
architectures used in NLP include:
1. Recurrent Neural Networks (RNNs): RNNs are designed for sequential data, making them
suitable for tasks like text generation, translation, and sentiment analysis. They maintain a
memory (hidden state) of previous inputs, which helps in understanding context.
2. Long Short-Term Memory (LSTM) and Gated Recurrent Units (GRU): LSTMs and GRUs are
variants of RNNs that solve the vanishing gradient problem, allowing the model to learn long-
term dependencies. These models are widely used for sequence prediction tasks such as language
modeling, text classification, and named entity recognition.
3. Transformers: The Transformer model, introduced by Vaswani et al. in the paper "Attention is
All You Need," relies on the self-attention mechanism to model dependencies between words
regardless of their distance in a sentence. The Transformer architecture has become the
foundation for many state-of-the-art NLP models, such as BERT, GPT, and T5.
Text Classification: Assigning predefined categories to text documents, such as spam detection
and sentiment analysis.
Named Entity Recognition (NER): Identifying entities (names, dates, locations) within a text.
Sentiment analysis: Technique in natural language processing (NLP) used to determine the
emotional tone behind a body of text. It can classify text as positive, negative, or neutral, and is
often applied to understand opinions in social media posts, customer reviews, and other forms of
user-generated content
28
Code
Output
29
Practical - 10
Theory
Convolutional Neural Networks (CNNs) are a class of deep neural networks used primarily for
image recognition and classification. They are designed to automatically and adaptively learn spatial
hierarchies of features from input images. CNNs use convolutional layers to apply filters to the input
image, pooling layers to down-sample the feature maps, and fully connected layers to classify the
images.
Components of CNN:
1. Convolutional Layer: Applies a set of filters to the input image, generating feature maps.
2. Activation Function: Typically ReLU (Rectified Linear Unit) is used to introduce non-
linearity.
3. Pooling Layer: Reduces the spatial dimensions (width and height) of the feature maps (e.g.,
max pooling).
4. Fully Connected Layer: Flattens the output of the convolutional layers and makes predictions
based on learned features.
Code
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
30
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=5, validation_split=0.1)
Output
31