NN & DL Record Final
NN & DL Record Final
NAME :
REG NO :
2024-2025
This is to certify that this is a bonafide record of the work done
in the VI Semester.
AIM:
To write a python to perform a simple vector addition in tensor flow.
ALGORITHM:
1. Import the tensor flow library to access its functionalities.
2. Define the input vectors that you want to add together. These vectors can be created as
tensor flow tensors.
3. Use tensor flow operation to perform element-wise addition of the input vectors.
4. Create a tensor flow session to execute the computational graph.
5. Use the session to run the addition operation and obtain the result.
6. Print the result of the addition operation or use it for further computation.
PROGRAM:
Import tensorflow as tf
vector1 = tf.constant([1,2,3])
vector2 = tf.constant([4,5,6])
print(vector1)
print(vector2)
result = tf.add(vector1, vector2)
print("Result of vector addition:",result)
OUTPUT:
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
tf.Tensor([4 5 6], shape=(3,), dtype=int32)
Result of vector addition: tf.Tensor([5 7 9], shape=(3,), dtype=int32)
RESULT:
Thus the python program to perform the simple vector addition has executed successfully
using the tensor flow.
EXP.NO: 02 IMPLEMENT A REGRESSION MODEL IN KERAS
DATE:
AIM:
ALGORITHM:
import numpy as np
np.random.seed(0)
X = np.random.rand(100, 1)
y = 2 * X + 1 + np.random.randn(100, 1) * 0.1
model = Sequential()
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
predictions = model.predict(X_new)
print('Predictions:', predictions)
OUTPUT:
Predictions: [[1.4192846]
[2.024505 ]
[2.6137354]]
RESULT:
Thus the regression model using keras has been executed and the
output is verified successfully.
EXP NO: 3 IMPLEMENT A PERCEPTRON IN TENSORFLOW/ KERAS
ENVIRONMENT
DATE:
AIM:
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
import numpy as np
# Generate some sample data for a logical OR operation
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 1]) # Output labels (OR gate)
# Define a simple perceptron model
model = keras.Sequential([Dense(units=1, input_dim=2, activation='sigmoid'])
# Compile the model
model.compile(optimizer=SGD(learning_rate=0.1), loss='mean_squared_error',
metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=1000, verbose=0)
# Evaluate the model
loss, accuracy = model.evaluate(X, y)
print("Loss:", loss)
print("Accuracy:", accuracy)
# Make predictions
predictions = model.predict(X)
print("Predictions:")
print(predictions)
OUTPUT:
RESULT:
Thus, the above program for “perceptron” has been executed successfully.
EXP NO: 04 IMPLEMENT A FEED-FORWARD NETWORK IN
DATE: TENSORFLOW/KERAS.
AIM:
ALGORITHM:
PROGRAM:
model = keras.Sequential([
keras.layers.Input(shape=(input_size,)),
keras.layers.Dense(units=hidden_units, activation='sigmoid'),
# Output layer
keras.layers.Dense(units=output_units, activation='sigmoid')
])
loss='binary_crossentropy',
metrics=['accuracy'])
model.summary()
OUTPUT:
RESULT:
AIM:
ALGORITHM:
import tensorflow as tf
Dropout
model = keras.Sequential([
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
RESULT:
Thus the given program for implement an image classifier using CNN in
TensorFlow/Keras is executed and verified successfully.
EXP.NO:06
IMPROVE THE DEEP LEARNING MODEL BY FINE
TUNING HYPER PARAMETERS
DATE:
AIM:
To write a python program for improve the Deep learning model by fine tuning hyper
parameters.
ALGORITHM:
PROGRAM:
# Necessary imports
import numpy as np
X, y = make_classification(n_samples=1000, n_features=20,
n_informative=10, n_classes=2, random_state=42)
logreg = LogisticRegression()
# Instantiating the GridSearchCV object
logreg_cv.fit(X, y)
OUTPUT:
RESULT:
Thus the given program for improve the deep learning model by fine tuning hyper
parameters is executed and verified successfully.
EXP.NO:07 IMPLEMENT A TRANSFER LEARNING CONCEPT IN
IMAGE CLASSIFICATION
DATE:
AIM:
ALGORITHM:
PROGRAM:
import tensorflow as tf
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy',
metrics=['accuracy'])
# You can use your own dataset or a built-in dataset like CIFAR-10
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize pixel values to the range
[0, 1]
data_generator = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True)
OUTPUT:
Epoch 1/10
Epoch 2/10
Epoch 3/10
Epoch 4/10
Epoch 5/10
Epoch 7/10
Epoch 8/10
Epoch 9/10
Epoch 10/10
RESULT:
Thus the given program for the implementation of the transfer learning concept in
AIM:
To write a python program and to use a pre trained model on keras for transfer learning.
ALGORITHM:
1. Start the program.
2. Load cifar10 dataset.
3. Normalize pixel values to be between 0 and 1.
4. One-hot encode the labels.
5. Load pre-trained VGG16 model without the top layers (include_top=False).
6. Create a new model with VGG16 base and additional dense layers.
7. Compile the model.
8. Train the model.
9. Evaluate the model on test set.
PROGRAM:
import numpy as np
from keras.applications import VGG16
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.optimizers import Adam
layer.trainable = False
# Create a new model with VGG16 base and additional dense layers
model = Sequential([
base_model,
Flatten(),
Dense(512, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer=Adam(),loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
RESULT:
Thus the python program for using pre-trained model on keras for transfer learning has
been executed successfully.
EXP:NO:09 PERFORM SENTIMENT ANALYSIS USING RNN
DATE:
AIM:
ALGORITHM:
PROGRAM:
import numpy as np
importtensorflow as tf
fromtensorflow.keras.datasets import imdb
fromtensorflow.keras.preprocessing import sequence
fromtensorflow.keras.models import Sequential
fromtensorflow.keras.layers import Dense, Embedding, SimpleRNN
# Load the IMDB dataset
max_features = 10000 # Consider only the top 10,000 words
maxlen = 500 # Cut reviews after 500 words
batch_size = 32
print('Loading data...')
(input_train, y_train), (input_test, y_test) = imdb.load_data(
num_words=max_features)
print(len(input_train), 'train sequences')
print(len(input_test), 'test sequences')
# Pad sequences to a fixed length
print('Pad sequences (samples x time)')
input_train = sequence.pad_sequences(input_train, maxlen=maxlen)
input_test = sequence.pad_sequences(input_test, maxlen=maxlen)
print('input_train shape:', input_train.shape)
print('input_test shape:', input_test.shape)
# Define the RNN model
model = Sequential()
model.add(Embedding(max_features, 32))
model.add(SimpleRNN(32))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model
print('Training...')
model.fit(input_train, y_train,
batch_size=batch_size,
epochs=5,
validation_data=(input_test, y_test))
# Evaluate the model
print('Evaluating...')
loss, accuracy = model.evaluate(input_test, y_test, verbose=0)
print('Test loss:', loss)
print('Test accuracy:', accuracy)
OUTPUT:
RESULT:
Thus to perform sentiment analysis using RNN was executed successfully.
EXP NO:10
DATE: IMPLEMENT AN LSTM BASED AUTOENCODER IN
TENSORFLOW / KERAS
AIM:
ALGORITHM:
PROGRAM:
import numpy as np
import tensorflow as tf
seq_length = 10
num_features = 5
num_samples = 1000
# Encoder
# Bottleneck
encoded = RepeatVector(seq_length)(encoder)
# Decoder
# Output
output_seq=
tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(num_features))(decoder )
# Autoencoder model
autoencoder.compile(optimizer='adam', loss='mse')
# Reconstruction
reconstructed_seqs = autoencoder.predict(X_test)
print("Original Sequence:")
print(X_test[0])
print("\nReconstructed Sequence:")
print(reconstructed_seqs[0])
OUTPUT:
RESULT:
Thus, the python program for implementing the LSTM based on autoencoder
has been executed successfully.
EX.NO:11
IMAGE GENERATION USING GAN
DATE:
AIM:
ALGORITHM:
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# Load MNIST dataset
(train_images, _), (_, _) = tf.keras.datasets.mnist.load_data()
# Preprocess data
train_images = train_images.reshape(train_images.shape[0], 28, 28,
1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize to [-1, 1]
# Define generator model
def make_generator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(7*7*256, use_bias=False,input_shape=(100,)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256)
# Note: None is the batch size
model.add(tf.keras.layers.Conv2DTranspose(128, (5, 5), strides=(1, 1),
padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(64, (5, 5), strides=(2, 2),
padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2),
padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)
return model
# Generate an image using the generator
def generate_and_show_image(generator):
noise = tf.random.normal([1, 100])
generated_image = generator.predict(noise)[0, :, :, 0]
plt.imshow(generated_image, cmap='gray')
plt.axis('off')
plt.show()
# Create and display a generated image
generator = make_generator_model()
generate_and_show_image(generator)
OUTPUT:
RESULT:
Thus the above program for image generation using GAN has
been executed successfully.
EXP.NO : 12
TRAIN A DEEP LEARNING MODEL TO CLASSIFY A
DATE : GIVEN IMAGE USING PRE – TRAINED MODEL
AIM :
To train a deep learning model to classify a given image using pre – trained
model
ALGORITHM :
PROGRAM :
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(32,
32, 3))
# Add custom classification layers on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x) # 10 classes in CIFAR-10
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam',loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
OUTPUT :
RESULT :
Thus to train a deep learning model to classify a given image using pre –
trained model was executed successfully.
EXP NO:13
RECOMMENDATION SYSTEM FROM SALES DATA USING DEEP
DATE:
LEARNING
AIM:
To write a python program for Recommendation system from sales data
using deep learning.
ALGORITHM:
1. Import the necessary libraries.
2. Load and preprocess the CIFAR-10 dataset.
3. Load a pre-trained model(MobileNetV2) excluding the top
classification layers.
4. Add custom classification layers on the top of the pre-trained model.
5. Freeze the layers of the pre-trained model.
6. Compile the model.
7. Train the model.
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize pixel values to the
range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Load a pre-trained model (MobileNetV2) excluding the top classification
layers
base_model = MobileNetV2(weights='imagenet', include_top=False,
input_shape=(32, 32, 3))
# Add custom classification layers on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x) # 10 classes in CIFAR-10
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
OUTPUT:
RESULT:
Thus the python program for Recommendation system from sales data
using deep learning has been executed successfully.
EX.NO:14
OBJECT DETECTION USING CNN
DATE:
AIM:
To write a python program to implement object detection using CNN.
ALGORITHM:
1.Start the program.
2.Import necessary libraries.
3.Randomly put handwritten digits from MNIST.
4.Pickup random index and make digit colorful.
5.Pickup a random position for a digit and place the digit.
6.Use the handwritten digits to train the model.
7.Test the model by giving an input to the model.
8.Plot the image using imshow() function.
9.Stop the program.
PROGRAM:
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import cv2
import matplotlib.pyplot as plt
(X_num, y_num), _ = tf.keras.datasets.mnist.load_data()
X_num = np.expand_dims(X_num, axis=-1).astype(np.float32) / 255.0
grid_size = 16 # image_size / mask_size
channels[0] = 1.0
channels[1] = px - (mx * grid_size) # x1
channels[2] = py - (my * grid_size) # y1
channels[3] = 28.0 # x2, in this demo image only 28 px as width
channels[4] = 28.0 # y2, in this demo image only 28 px as height
channels[5 + kls] = 1.0
# put digit in X
X[py:py+28, px:px+28] += number
def make_data(size=64):
X = np.zeros((size, 128, 128, 3), dtype=np.float32)
y = np.zeros((size, 8, 8, 15), dtype=np.float32)
for i in range(size):
make_numbers(X[i], y[i])
def get_color_by_probability(p):
if p < 0.3:
return (1., 0., 0.)
if p < 0.7:
return (1., 1., 0.)
return (0., 1., 0.)
def show_predict(X, y, threshold=0.1):
X = X.copy()
for mx in range(8):
for my in range(8):
channels = y[my][mx]
prob, x1, y1, x2, y2 = channels[:5]
# if prob < threshold we won't show any thing
if prob < threshold:
continue
color = get_color_by_probability(prob)
# bounding box
px, py = (mx * grid_size) + x1, (my * grid_size) + y1
cv2.rectangle(X, (int(px), int(py)), (int(px + x2), int(py + y2)), color, 1)
# label
cv2.rectangle(X, (int(px), int(py - 10)), (int(px + 12), int(py)), color, -1)
kls = np.argmax(channels[5:])
cv2.putText(X, f'{kls}', (int(px + 2), int(py-2)),
cv2.FONT_HERSHEY_PLAIN, 0.7, (0.0, 0.0, 0.0))
plt.imshow(X)
# test
X, y = make_data(size=1)
show_predict(X[0], y[0])
OUTPUT:
RESULT:
Thus,the python program for the implementation of object detection using
CNN has been executed successfully.
EXP.NO:15
IMPLEMENT ANY SIMPLE REINFORCEMENT ALGORITHM
DATE; FOR AN NLP PROBLEM
AIM:
Write a python program to implement any simple reinforcement algorithm for an NLP
problem.
ALGORITHM:
1. Start The Program.
4. Exploitation rate: choose the action with the highest Q-value & choose the action with
the highest Q-value.
QLearningAgent:
self.actions = actions
else:
return np.random.choice(self.actions)
else:
self.q_table[state] = {action: 0}
if next_state not in self.q_table:
def extract_features(text):
features = {}
features[word] = features.get(word, 0) + 1
return features
if sentiment == predicted_sentiment:
training_data = [
#c
state = extract_features(text)
action = agent.choose_action(str(state))
test_data = [
state = extract_features(text)
action = agent.choose_action(str(state))
RESULT:
Thus the python program to implement the simple reinforcement algorithm for an NLP