Deep Learning
Deep Learning
GREATER NOIDA
List of Experiment
import torch
import torch.nn as nn
import torch.optim as optim
self.linear = nn.Linear(input_size, 1)
self.sigmoid = nn.Sigmoid()
x = self.sigmoid(x)
return x
# Example data
X_train = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y_train = torch.tensor([[0], [0], [0], [1]], dtype=torch.float32)
input_size = 2
perceptron = Perceptron(input_size)
# Define loss function and optimizer
criterion = nn.BCELoss()
optimizer = optim.SGD(perceptron.parameters(), lr=0.1)
# Training loop
epochs = 1000
for epoch in range(epochs):
# Forward pass
outputs = perceptron(X_train)
# Calculate loss
optimizer.step()
if (epoch+1) % 100 == 0:
print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')
output
Epoch [100/1000], Loss: 0.5207
Epoch [200/1000], Loss: 0.5048
Epoch [300/1000], Loss: 0.4953
Epoch [400/1000], Loss: 0.4884
# Standardize features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Make predictions
predictions = model.predict(X_test_scaled)
output
Epoch 1/100
4/4 - 0s - loss: 1.1635 - accuracy: 0.3500
Epoch 2/100
4/4 - 0s - loss: 1.0796 - accuracy: 0.3500
...
Epoch 100/100
4/4 - 0s - loss: 0.2013 - accuracy: 0.9667
Test Accuracy: 1.0
Practical- 3
3.write a program to implement a convolution neural networks CNN in Keras.
perform predictions using the train convolution neural network (CNN).
CODE:-
import numpy as np
import tensorflow as tf
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Make predictions
predictions = model.predict(X_test)
output
The output of the code will show the training progress, test accuracy, and will not directly
display predictions. Here's how the output might look:
Epoch 1/5
938/938 [==============================] - 30s 32ms/step - loss: 0.1701 - accuracy:
0.9498
Epoch 2/5
Epoch 5/5
938/938 [==============================] - 29s 31ms/step - loss: 0.0200 - accuracy:
0.9939
Test Accuracy: 0.9901000261306763
# other imports
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout
for i in range(5):
for j in range(5):
ax[i][j].imshow(x_train[k], aspect='auto')
k += 1
plt.show()
output-
# number of classes
K = len(set(y_train))
print("number of classes:", K)
# Build the model using the functional API
# input layer
i = Input(shape=x_train[0].shape)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(i)
x = BatchNormalization()(x)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
x = BatchNormalization()(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
x = MaxPooling2D((2, 2))(x)
x = Flatten()(x)
x = Dropout(0.2)(x)
# Hidden layer
x = Dense(1024, activation='relu')(x)
x = Dropout(0.2)(x)
# last hidden layer i.e.. output layer
x = Dense(K, activation='softmax')(x)
model = Model(i, x)
# model description
model.summary()
ouput-
Practical- 4
a. Write a program to perform face detection using CNN.
CODE:-
import cv2
import numpy as np
layers.Dense(10, activation='softmax')
])
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# Summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
output:-
0.894000 (0.004000) with: {'dropout_rate': 0.1, 'kernel_size': 3, 'learning_rate': 0.001,
'num_filters': 16}
0.900500 (0.003500) with: {'dropout_rate': 0.1, 'kernel_size': 3, 'learning_rate': 0.001,
'num_filters': 32}
...
self.output_nodes = output_nodes
# Initialize weights
self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5,
(self.input_nodes, self.hidden_nodes))
# as shown below.
# self.activation_function = lambda x: 0 # Replace 0 with your sigmoid calculation.
### If the lambda code above is not something you're familiar with,
# You can uncomment out the following three lines and put your
self.activation_function = sigmoid
def train(self, features, targets):
''' Train the network on batch of features and targets.
Arguments
--------
features: 2D array, each row is one data record, each column is a feature
targets: 1D array of target values
'''
n_records = features.shape[0]
delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)
delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape)
for X, y in zip(features, targets):
Arguments
---------
X: features batch
'''
#### Implement the forward pass here ####
### Forward pass ###
# TODO: Hidden layer - Replace these values with your calculations.
Arguments
---------
final_outputs: output from forward pass
# TODO: Backpropagated error terms - Replace these values with your calculations.
output_error_term = error
Arguments
---------
'''
Arguments
---------
features: 1D array of feature values
'''
# TODO: Output layer - Replace these values with the appropriate calculations.
final_inputs = hidden_outputs # signals into final output layer
final_outputs = self.forward_pass_train(hidden_inputs)[0] # signals from final output
layer
return final_outputs
#########################################################
# Set your hyperparameters here
##########################################################
iterations = 5000
learning_rate = 0.56
hidden_nodes = 32
output_nodes = 1
Practical- 5
Write a program to build auto-encoder in keras
CODE:-
import numpy as np
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# Once trained, you can use the encoder part to get the encoded representation of the input
data
encoder = Model(input_layer, encoded)
encoded_data = encoder.predict(data)
# You can also use the decoder part to reconstruct the input data from the encoded
representation
encoded_input = Input(shape=(encoding_dim,))
decoder_layer = autoencoder.layers[-1]
output-
Practical - 6
Write a program to implement basic reinforcement learning algorithm to teach
a bot to reach its destination.
CODE:-
import numpy as np
# Define actions
ACTIONS = ['UP', 'DOWN', 'LEFT', 'RIGHT']
# Define rewards
REWARDS = {
(3, 4): 100, # Reward for reaching the destination
(1, 1): -10, # Penalty for entering a specific state
(2, 2): -5 # Penalty for entering a specific state
# Initialize Q-values
Q_values = np.zeros((GRID_SIZE, GRID_SIZE, len(ACTIONS)))
# Define parameters
LEARNING_RATE = 0.1
DISCOUNT_FACTOR = 0.9
EPISODES = 1000
EPSILON = 0.1
# Function to choose action using epsilon-greedy policy
def choose_action(state):
Q_values[state[0]][state[1]][ACTIONS.index(action)] += \
LEARNING_RATE * (reward + DISCOUNT_FACTOR * max_next_reward -
Q_values[state[0]][state[1]][ACTIONS.index(action)])
def run_episode():
state = START_STATE
while state != END_STATE:
action = choose_action(state)
next_state = state
if action == 'UP':
next_state = (max(state[0] - 1, 0), state[1])
reward = REWARDS[next_state]
return path
# Print the optimal path
optimal_path = get_optimal_path()
CODE:-
import numpy as np
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
hidden_size = 4
output_size = 2
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
data = np.random.randn(1000, 1)
X, y = [], []
for i in range(len(data)):
end_ix = i + n_steps
if end_ix > len(data)-1:
break
X.append(data[i:end_ix, 0])
y.append(data[end_ix, 0])
return np.array(X), np.array(y)
n_steps = 3
X, y = prepare_data(data, n_steps)
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(n_steps, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
# Make predictions
self.size = size
self.bot_position = 0
# Calculate reward
if self.bot_position == self.size - 1:
reward = 1 # Destination reached
done = True
else:
reward = 0
done = False
self.hidden_size = hidden_size
self.output_size = output_size
# Initialize weights
# Forward pass
h = np.tanh(np.dot(self.Wxh, x) + np.dot(self.Whh, h_prev) + self.bh)
y = np.dot(self.Why, h) + self.by
return h, y
def main():
# Define the environment and bot
env = Environment(size=5)
rnn = RNN(input_size=1, hidden_size=10, output_size=2)
# Training loop
num_episodes = 1000
for episode in range(num_episodes):
state = np.array([[env.bot_position]])
action_probs = rnn.forward(state)[1]
action = np.random.choice(range(env.size), p=action_probs.ravel())
if done:
print(f"Episode {episode+1}: Destination reached!")
break
if __name__ == "__main__":
main()
Output:
CODE:-
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
X.append(data[i:i+time_steps])
y.append(data[i+time_steps])
return np.array(X), np.array(y)
def build_lstm_model(time_steps):
model = Sequential()
model.add(LSTM(units=50, input_shape=(time_steps, 1)))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mse')
return model
plt.ylabel('Loss')
plt.title('Training Loss History')
plt.legend()
plt.show()
# Main function
def main():
# Generate time series data
num_points = 1000
time_steps = 10
data = generate_time_series_data(num_points)
X, y = prepare_data_for_lstm(data, time_steps)
epochs = 100
history = train_lstm_model(lstm_model, X_train, y_train, epochs)
plot_loss_history(history)
if __name__ == "__main__":
main()
Output:
Practical- 9
CODE:-
import numpy as np
return 1 / (1 + np.exp(-x))
def relu(x):
return np.maximum(0, x)
def tanh(x):
return np.tanh(x)
def softmax(x):
x = np.linspace(-5, 5, 100)
y_relu = relu(x)
y_tanh = tanh(x)
# Plot activation functions
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.plot(x, y_sigmoid, label='Sigmoid')
plt.title('Sigmoid Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(x, y_relu, label='ReLU')
plt.title('ReLU Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.subplot(2, 2, 3)
plt.plot(x, y_tanh, label='Tanh')
plt.tight_layout()
plt.show()
Output:
b) write a program in TensorFlow to demonstrate different loss functions.
CODE:-
import tensorflow as tf
import numpy as np
# Sample data (you can replace this with your actual data)
# Hyperparameters
learning_rate = 0.01
epochs = 100
X = iris.data # Features
y = iris.target # Target labels (one-hot encoded later)
super(ANN, self).__init__()
self.hidden_layer = tf.keras.layers.Dense(10, activation='relu') # Hidden layer with 10
neurons
self.output_layer = tf.keras.layers.Dense(num_classes) # Output layer with 3 neurons for 3
classes
output = self.output_layer(x)
return output
# Training loop
for epoch in range(epochs):
with tf.GradientTape() as tape:
predictions = model(X_train)
loss = loss_fn(y_train, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# Print output
print(f"Test Loss: {loss:.4f}, Test Accuracy: {accuracy:.4f}")
Output: