0% found this document useful (0 votes)
2 views17 pages

Deep Learning

The document outlines a series of practical exercises focused on implementing various deep learning techniques using TensorFlow. It includes tasks such as creating and manipulating tensors, building neural networks for binary and multiclass classification, image segmentation, and applying autoencoders and GANs. Each practical aims to reinforce concepts through coding examples and model training on toy datasets.

Uploaded by

shadab niyazi
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)
2 views17 pages

Deep Learning

The document outlines a series of practical exercises focused on implementing various deep learning techniques using TensorFlow. It includes tasks such as creating and manipulating tensors, building neural networks for binary and multiclass classification, image segmentation, and applying autoencoders and GANs. Each practical aims to reinforce concepts through coding examples and model training on toy datasets.

Uploaded by

shadab niyazi
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

INDEX

Sr No. Practicals Signature

1. A. Create tensors with different shapes and data types. Perform


basic operations like addition, subtraction, multiplication, and
division on tensors. Reshape, slice, and index tensors to extract
specific elements or sections. Performing matrix multiplication
and finding eigenvectors and eigenvalues using TensorFlow.

B. Program to solve the XOR problem.


2. A. Implement a simple linear regression model using
TensorFlow's low-level API (or tf. keras). Train the model on a
toy dataset (e.g., housing prices vs. square footage). Visualize the
loss function and the learned linear relationship. Make predictions
on new data points.
3. A. Implementing deep neural network for performing binary
classification task

B. Using a deep feed-forward network with two hidden layers for


performing multiclass
B. classification and predicting the class.
4. Write a program to implement deep learning Techniques for
image segmentation

5. Applying the Autoencoder algorithms for encoding real-world


data

6. Write a program for character recognition using RNN and


compare it with CNN.

7. Write a program to develop Autoencoders using MNIST


Handwritten Digits

8. Demonstrate recurrent neural network that learns to perform


sequence analysis for stock price.(google stock price)

9. Applying Generative Adversarial Networks for image generation


and unsupervised tasks.
PRACTICAL NO: 1.A

Aim: Create tensors with different shapes and data types. Perform basic
operations like addition, subtraction, multiplication, and division on tensors.
Reshape, slice, and index tensors to extract specific elements or sections.
Performing matrix multiplication and finding eigenvectors and eigenvalues using
TensorFlow

import tensorflow as tf

# Create tensors with different shapes and data types


tensor_1d = [Link]([1, 2, 3], dtype=tf.int32)
tensor_2d = [Link]([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)
tensor_3d = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=tf.float64)

print("1D Tensor (int32):", tensor_1d)


print("2D Tensor (float32):\n", tensor_2d)
print("3D Tensor (float64):\n", tensor_3d)

# Basic arithmetic operations


a = [Link]([[1, 2], [3, 4]], dtype=tf.float32)
b = [Link]([[5, 6], [7, 8]], dtype=tf.float32)

add = [Link](a, b)
sub = [Link](a, b)
mul = [Link](a, b)
div = [Link](a, b)

print("\nAddition:\n", add)
print("Subtraction:\n", sub)
print("Element-wise Multiplication:\n", mul)
print("Division:\n", div)

# Reshape, slice, and index


reshaped = [Link](tensor_2d, [1, 4])
sliced = tensor_2d[1, :] # Second row
indexed = tensor_2d[0, 1] # First row, second column

print("\nReshaped (2x2 -> 1x4):\n", reshaped)


print("Sliced Row 2:", sliced)
print("Indexed Element [0,1]:", [Link]())

# Matrix multiplication and eigenvalues/vectors


mat = [Link]([[4.0, 2.0], [2.0, 3.0]], dtype=tf.float32)
matmul = [Link](mat, mat)
eigen_values, eigen_vectors = [Link](mat)

print("\nMatrix Multiplication:\n", matmul)


print("Eigenvalues:", eigen_values.numpy())
print("Eigenvectors:\n", eigen_vectors.numpy())
OUTPUT:
PRACTICAL NO: 1.B

AIM: Program to solve the XOR problem


import tensorflow as tf
import numpy as np
# Input and output data for XOR
X = [Link]([[0, 0],[0, 1],[1, 0],[1, 1]], dtype=np.float32)
y = [Link]([[0],[1],[1],[0]], dtype=np.float32)
# Create a simple neural network model
model = [Link]([
[Link](4, activation='sigmoid', input_shape=(2,)),
[Link](1, activation='sigmoid')
])
# Compile the model
[Link](optimizer='adam', loss='mse')
# Train the model
[Link](X, y, epochs=1000, verbose=0)
# Predict on training data
predictions = [Link](X)
# Output predictions
print("Predicted Outputs:")
print([Link](predictions).astype(int))
print("\nActual Outputs:")
print([Link](int))

OUTPUT:
PRACTICAL NO: 2.A

AIM: Implement a simple linear regression model using


TensorFlow's low- level API (or tf. keras). Train the model on a toy
dataset (e.g., housing prices vs. square footage). Visualize the loss
function and the learned linear relationship. Make predictions on
new data points.

import tensorflow as tf
import numpy as np
import [Link] as plt

# Toy dataset: square footage vs house price (in 1000s of dollars)


X = [Link]([50, 80, 100, 120, 150, 200], dtype=np.float32)
y = [Link]([150, 220, 250, 300, 350, 450], dtype=np.float32)
# Reshape input for TensorFlow (batch_size, features)
X = [Link](-1, 1)
# Build model
model = [Link]([
[Link](1, input_shape=(1,))
])
# ✅ Compile model using Adam optimizer to prevent NaNs
[Link](optimizer='adam', loss='mean_squared_error')
# Train model
history = [Link](X, y, epochs=500, verbose=0)
# Plot training loss
[Link]([Link]['loss'])
[Link]('Loss Curve')
[Link]('Epochs')
[Link]('Loss')
[Link](True)
[Link]()
# Plot the learned linear regression line
[Link](X, y, label='Data Points')
[Link](X, [Link](X), color='red', label='Fitted Line')
[Link]('Linear Regression Fit')
[Link]('Square Footage')
[Link]('Price (in $1000)')
[Link]()
[Link](True)
[Link]()
# Predict new data points
new_X = [Link]([[75], [130], [180]], dtype=np.float32)
predicted_prices = [Link](new_X)
# ✅ Print predicted prices clearly
print("Predicted Prices:")
for i in range(len(new_X)):
sqft = new_X[i][0]
price = predicted_prices[i][0]
print(f"House Size: {sqft} sqft\tPredicted Price: ${price:.2f} K")
OUTPUT:

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 48ms/step

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 47ms/step

Predicted Prices:
House Size: 75.0 sqft Predicted Price: $-49.50 K
House Size: 130.0 sqft Predicted Price: $-86.16 K
House Size: 180.0 sqft Predicted Price: $-119.48 K
PRACTICAL NO: 3.A

AIM: Convolutional Neural Networks (Classification) practical


3A .Implementing deep neural network for performing binary
classification task
import tensorflow as tf
import numpy as np
import [Link] as plt

# Step 1: Create a toy dataset


# 100 samples, each with 10 features, binary labels (0 or 1)
X = [Link](100, 10).astype(np.float32) # Features
y = [Link](2, size=(100, 1)) # Labels: 0 or 1

# Step 2: Build the deep neural network model


model = [Link]([
[Link](64, activation='relu', input_shape=(10,)),
[Link](32, activation='relu'),
[Link](16, activation='relu'),
[Link](1, activation='sigmoid') # Output layer for binary classification
])

# Step 3: Compile the model


[Link](optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Step 4: Train the model
history = [Link](X, y, epochs=20, batch_size=16, validation_split=0.2)

# Step 5: Plot training and validation accuracy


[Link]([Link]['accuracy'], label='Train Acc')
[Link]([Link]['val_accuracy'], label='Val Acc')
[Link]('Model Accuracy')
[Link]('Epochs')
[Link]('Accuracy')
[Link]()
[Link](True)
[Link]()
# Step 6: Predict on new data
new_data = [Link](3, 10).astype(np.float32)
predictions = [Link](new_data)
# Step 7: Output predictions
print("Predicted Probabilities:")
for i, pred in enumerate(predictions):
print(f"Sample {i+1}: {pred[0]:.4f} → Class {int(pred[0] > 0.5)}")

OUTPUT:

5/5 ━━━━━━━━━━━━━━━━━━━━ 2s 71ms/step - accuracy: 0.5122 -


loss: 0.6978 - val_accuracy: 0.4000 - val_loss: 0.7219
Epoch 2/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 18ms/step - accuracy:
0.3793 - loss: 0.7213 - val_accuracy: 0.4000 - val_loss: 0.7091
Epoch 3/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 17ms/step - accuracy:
0.4424 - loss: 0.7012 - val_accuracy: 0.3000 - val_loss: 0.7030
Epoch 4/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 16ms/step - accuracy:
0.3950 - loss: 0.6946 - val_accuracy: 0.4500 - val_loss: 0.6979
Epoch 5/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 20ms/step - accuracy:
0.5281 - loss: 0.6879 - val_accuracy: 0.6000 - val_loss: 0.6922
Epoch 6/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 17ms/step - accuracy:
0.6160 - loss: 0.6826 - val_accuracy: 0.6000 - val_loss: 0.6887
Epoch 7/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 16ms/step - accuracy:
0.6248 - loss: 0.6770 - val_accuracy: 0.5500 - val_loss: 0.6867
Epoch 8/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 17ms/step - accuracy:
0.5677 - loss: 0.6782 - val_accuracy: 0.6000 - val_loss: 0.6857
Epoch 9/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 16ms/step - accuracy:
0.5547 - loss: 0.6791 - val_accuracy: 0.6000 - val_loss: 0.6849
Epoch 10/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 17ms/step - accuracy:
0.6033 - loss: 0.6694 - val_accuracy: 0.6000 - val_loss: 0.6841
Epoch 11/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 18ms/step - accuracy:
0.5686 - loss: 0.6696 - val_accuracy: 0.6000 - val_loss: 0.6838
Epoch 12/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 16ms/step - accuracy:
0.5833 - loss: 0.6691 - val_accuracy: 0.6500 - val_loss: 0.6837
Epoch 13/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 18ms/step - accuracy:
0.5720 - loss: 0.6679 - val_accuracy: 0.6500 - val_loss: 0.6842
Epoch 14/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 25ms/step - accuracy:
0.5814 - loss: 0.6665 - val_accuracy: 0.6500 - val_loss: 0.6835
Epoch 15/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 26ms/step - accuracy:
0.5519 - loss: 0.6783 - val_accuracy: 0.6500 - val_loss: 0.6842
Epoch 16/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 33ms/step - accuracy:
0.5936 - loss: 0.6650 - val_accuracy: 0.6500 - val_loss: 0.6843
Epoch 17/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 33ms/step - accuracy:
0.5502 - loss: 0.6741 - val_accuracy: 0.6500 - val_loss: 0.6849
Epoch 18/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 35ms/step - accuracy:
0.5556 - loss: 0.6682 - val_accuracy: 0.6500 - val_loss: 0.6849
Epoch 19/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 25ms/step - accuracy:
0.5927 - loss: 0.6664 - val_accuracy: 0.6500 - val_loss: 0.6853
Epoch 20/205/5 ━━━━━━━━━━━━━━━━━━━━ 0s 37ms/step - accuracy:
0.6014 - loss: 0.6610 - val_accuracy: 0.6500 - val_loss: 0.6857

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


Predicted Probabilities:
Sample 1: 0.3659 → Class 0
Sample 2: 0.4790 → Class 0
Sample 3: 0.5033 → Class 1
PRACTICAL NO: 3.B

AIM: Using a deep feed-forward network with two hidden layers for
performing multiclass classification and predicting the class.
import tensorflow as tf
from [Link] import layers, models
import numpy as np

# Toy multiclass dataset: 100 flattened images (e.g., 32x32 RGB → 3072 features)
X_train_multi = [Link](100, 3072).astype(np.float32)
y_train_multi = [Link](3, size=(100,)) # 3 classes: 0, 1, 2

# Build FFN with 2 hidden layers


model_multiclass = [Link]([
[Link](128, activation='relu', input_shape=(3072,)),
[Link](64, activation='relu'),
[Link](3, activation='softmax') # 3 output classes
])

# Compile model
model_multiclass.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Train the model


model_multiclass.fit(X_train_multi, y_train_multi, epochs=5, batch_size=16, validation_split=0.2)

# Predict class probabilities for 3 samples


preds_multi = model_multiclass.predict(X_train_multi[:3])
print("Predicted Class Probabilities:\n", preds_multi)

OUTPUT:
PRACTICAL NO: 4

AIM: Write a program to implement deep learning Techniques for


image segmentation.

import tensorflow as tf
from [Link] import layers, models
import numpy as np

# Toy dataset: 100 RGB images of size 128x128, binary masks


X_train = [Link](100, 128, 128, 3).astype(np.float32)
y_train = [Link](2, size=(100, 128, 128, 1)).astype(np.float32)

# Define simplified U-Net


def simple_unet(input_shape):
inputs = [Link](shape=input_shape)

# Encoder
conv1 = layers.Conv2D(16, 3, activation='relu', padding='same')(inputs)
pool1 = layers.MaxPooling2D(pool_size=(2, 2))(conv1)

conv2 = layers.Conv2D(32, 3, activation='relu', padding='same')(pool1)


pool2 = layers.MaxPooling2D(pool_size=(2, 2))(conv2)

# Bottleneck
conv3 = layers.Conv2D(64, 3, activation='relu', padding='same')(pool2)

# Decoder
up4 = layers.Conv2DTranspose(32, 2, strides=(2, 2), padding='same')(conv3)
concat4 = [Link]([up4, conv2], axis=-1)
conv4 = layers.Conv2D(32, 3, activation='relu', padding='same')(concat4)

up5 = layers.Conv2DTranspose(16, 2, strides=(2, 2), padding='same')(conv4)


concat5 = [Link]([up5, conv1], axis=-1)
conv5 = layers.Conv2D(16, 3, activation='relu', padding='same')(concat5)

# Output layer
outputs = layers.Conv2D(1, 1, activation='sigmoid')(conv5)

return [Link](inputs=inputs, outputs=outputs)

# Create model
model = simple_unet((128, 128, 3))

# Compile model
[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Train the model


[Link](X_train, y_train, batch_size=8, epochs=5, validation_split=0.2)

# Predict on one sample


sample_input = X_train[:1]
prediction = [Link](sample_input)

print("Predicted Mask Shape:", [Link])


print("Sample Prediction (first 3x3 pixels):\n", prediction[0, :3, :3, 0])
OUTPUT:
PRACTICAL NO: 6

AIM: Applying the Autoencoder algorithms for encoding real-world


data.
import numpy as np
import tensorflow as tf
from [Link] import Input, Dense
from [Link] import Model

# Simulated real-world data: 1000 samples, each with 10 features


X = [Link](1000, 10).astype('float32')

# Define autoencoder architecture


input_dim = 10
encoding_dim = 3 # Compressed representation

# Encoder
input_layer = Input(shape=(input_dim,))
encoded = Dense(encoding_dim, activation='relu')(input_layer)

# Decoder
decoded = Dense(input_dim, activation='sigmoid')(encoded)

# Autoencoder model
autoencoder = Model(inputs=input_layer, outputs=decoded)
[Link](optimizer='adam', loss='mse')

# Train
[Link](X, X, epochs=10, batch_size=16, shuffle=True, verbose=0)

# Predict (encode + decode)


sample = X[0].reshape(1, -1)
reconstructed = [Link](sample)

# Output
print("Original Data:\n", sample)
print("\nReconstructed Data:\n", reconstructed)

OUTPUT:
PRACTICAL NO: 7

AIM: Write a program for character recognition using RNN and


compare it with CNN.
import tensorflow as tf
from [Link] import layers, models

# Load & normalize MNIST


(x_train, y_train), _ = [Link].load_data()
x_train = x_train / 255.0

# RNN model (input shape: (28 timesteps, 28 features))


rnn = [Link]([
[Link](64, input_shape=(28, 28)),
[Link](10, activation='softmax')
])
[Link](optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# CNN model (input shape: (28, 28, 1))


cnn = [Link]([
layers.Conv2D(16, 3, activation='relu', input_shape=(28, 28, 1)),
[Link](),
[Link](10, activation='softmax')
])
[Link](optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train on small subset


x_small, y_small = x_train[:1000], y_train[:1000]
[Link](x_small, y_small, epochs=2, verbose=0)
[Link](x_small.reshape(-1, 28, 28, 1), y_small, epochs=2, verbose=0)

# Evaluate
rnn_acc = [Link](x_train, y_train, verbose=0)[1]
cnn_acc = [Link](x_train.reshape(-1, 28, 28, 1), y_train, verbose=0)[1]

print("RNN Accuracy:", rnn_acc)


print("CNN Accuracy:", cnn_acc)

OUTPUT:
PRACTICAL NO: 8

AIM: Write a program to develop Autoencoders using MNIST


Handwritten Digits.
import tensorflow as tf
from [Link] import layers, models

# Step 1: Load and normalize MNIST data


(x_train, _), _ = [Link].load_data()
x_train = x_train / 255.0 # Normalize to [0, 1]

# Step 2: Flatten images (28x28 = 784)


x_train_flat = x_train.reshape(-1, 28 * 28)

# Step 3: Define Autoencoder model


autoencoder = [Link]([
[Link](32, activation='relu', input_shape=(784,)), # Encoder
[Link](784, activation='sigmoid') # Decoder
])

# Step 4: Compile the model


[Link](optimizer='adam', loss='binary_crossentropy')

# Step 5: Train the model


[Link](x_train_flat, x_train_flat, epochs=5, batch_size=128, verbose=1)

# Step 6: Reconstruct a sample digit


sample = x_train_flat[0].reshape(1, -1)
recon = [Link](sample)

# Step 7: Print original vs reconstructed values


print("Original (first 10 pixels):", sample[0, :10])
print("Reconstructed (first 10 pixels):", recon[0, :10])

OUTPUT:
PRACTICAL NO: 9

AIM: Demonstrate recurrent neural network that learns to perform


sequence analysis for stock price.(google stock price).
import numpy as np
import tensorflow as tf
from [Link] import SimpleRNN, Dense
from [Link] import Sequential

# Sample Google stock prices (replace with real historical prices if needed)
prices = [Link]([
1450.2, 1460.5, 1470.3, 1468.4, 1480.6,
1490.1, 1500.0, 1510.5, 1520.3, 1530.7,
1540.2, 1550.0, 1560.8, 1570.4, 1580.9
], dtype=np.float32)

# Prepare sequences
def create_sequences(data, seq_length):
X, y = [], []
for i in range(len(data) - seq_length):
[Link](data[i:i+seq_length])
[Link](data[i+seq_length])
return [Link](X), [Link](y)

SEQ_LENGTH = 5
X, y = create_sequences(prices, SEQ_LENGTH)

# Reshape for RNN: (samples, time_steps, features)


X = [Link](-1, SEQ_LENGTH, 1)

# Build RNN model


model = Sequential([
SimpleRNN(32, input_shape=(SEQ_LENGTH, 1)),
Dense(1)
])

[Link](optimizer='adam', loss='mse')

# Train the model


[Link](X, y, epochs=50, verbose=0)

# Predict next price after last known sequence


last_seq = prices[-SEQ_LENGTH:].reshape(1, SEQ_LENGTH, 1)
predicted_price = [Link](last_seq, verbose=0)

# Output results
print("Last Known Sequence:", prices[-SEQ_LENGTH:])
print("Predicted Next Price:", predicted_price[0][0])

OUTPUT:
PRACTICAL NO: 10

AIM: Applying Generative Adversarial Networks for image


generation and unsupervised tasks.
import tensorflow as tf
from [Link] import layers, models
import numpy as np

# Load and preprocess MNIST


(x_train, _), _ = [Link].load_data()
x_train = x_train / 255.0
x_train = x_train.reshape(-1, 28, 28, 1)

# Generator
def make_generator():
return [Link]([
[Link](7 * 7 * 128, input_dim=100),
[Link]((7, 7, 128)),
layers.Conv2DTranspose(64, 4, strides=2, padding='same', activation='relu'),
layers.Conv2DTranspose(1, 4, strides=2, padding='same', activation='sigmoid')
])

# Discriminator
def make_discriminator():
return [Link]([
layers.Conv2D(64, 5, strides=2, padding='same', input_shape=(28, 28, 1)),
[Link](0.2),
layers.Conv2D(128, 5, strides=2, padding='same'),
[Link](0.2),
[Link](),
[Link](1, activation='sigmoid')
])

# Create models
generator = make_generator()
discriminator = make_discriminator()
[Link](optimizer='adam', loss='binary_crossentropy')

# GAN model
[Link] = False
gan = [Link]([generator, discriminator])
[Link](optimizer='adam', loss='binary_crossentropy')

# Very short training loop for demo (3 steps)


for step in range(3):
idx = [Link](0, x_train.shape[0], 32)
real = x_train[idx]

noise = [Link](32, 100)


fake = [Link](noise, verbose=0)

labels_real = [Link]((32, 1))


labels_fake = [Link]((32, 1))

d_loss_real = discriminator.train_on_batch(real, labels_real)


d_loss_fake = discriminator.train_on_batch(fake, labels_fake)

# Generator wants to fool the discriminator


g_loss = gan.train_on_batch(noise, [Link]((32, 1)))

print(f"Step {step+1} - Discriminator Loss: {(d_loss_real + d_loss_fake)/2:.4f}, Generator Loss:


{g_loss:.4f}")
OUTPUT:

You might also like