Lab Manual - NNDL
Lab Manual - NNDL
No:1
DATE : VECTOR ADDITION WITH TENSORFLOW
AIM
To write a python program to implement simple vector addition in tensorflow
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python 3 as the
default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it. However, you can also
manually save your work by clicking on File > Save or using the shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
# Define two vectors as constants
vector1 = tf.constant([1.0, 2.0, 3.0])
vector2 = tf.constant([4.0, 5.0, 6.0])
# Add the vectors using the add operation
result = tf.add(vector1, vector2)
# Create a TensorFlow session
with tf.Session() as session:
# Run the computation and get the result
addition_result = session.run(result)
# Print the result
print(”Vector 1:”, addition_result[0])
print(“Vector 2:”, addition_result[1])
print(”Vector Sum:”, addition_result[2])
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:2
DATE : REGRESSION MODEL IN KERAS
AIM
To write a python program to implement a regression model in keras
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import numpy as np
import tensorflow as tf
y = 2 * X + 1 + 0.1 * np.random.rand(100, 1)
# Simulated linear relationship with noise
# Define the model architecture
model = keras.Sequential([
layers.Input(shape=(1,)), # Input layer
])
model.compile(optimizer='adam', loss='mean_squared_error')
#Train the model
model.fit(X, y, epochs=100, verbose=0) # You can adjust the number of epochs #
Evaluate the model (optional)
loss = model.evaluate(X, y)
print("Mean Squared Error:", loss)
#Make predictions
new_data = np.array([[0.5], [0.8], [1.0]]) # New data for prediction
predictions = model.predict(new_data)
print("Predictions:", predictions)
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:3
DATE : PERCEPTRON IN TENSORFLOW/KERAS
ENVIRONMENT
AIM
To write a python program to implement a perceptron in tensorflow/keras environment
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
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]]) # Input features
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') # 2 input features, 1 output
unit, sigmoid activation
])
# 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) # You can adjust the number of epochs
# 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:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:4
DATE :
FEED FORWARD NETWORK IN
TENSORFLOW/KERAS
AIM
To write a python program to implement a feed forward network in tensorflow/keras
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow.keras.layers
import Dense
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # Input features
Dense(units=4, input_dim=2, activation='relu'), # 2 input features, 4 hidden units with ReLU activation
])
y) print("Loss:", loss)
print("Accuracy:", accuracy)
# Make predictions
predictions = model.predict(X)
print("Predictions:")
print(predictions)
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:5
IMAGE CLASSIFIER USING CNN IN
DATE :
TENSORFLOW/KERAS
AIM
To write a python program to implement an image classifier using cnn in tensorflow/keras
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow import keras
y_test = to_categorical(y_test,10) #
model = keras.Sequential([
MaxPooling2D((2, 2)),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:6
DATE :
DEEP LEARNING MODEL BY FINE TUNING HYPER
PARAMETERS
AIM
To write a python program to improve the deep learning model by fine tuning hyper parameters
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
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]
model = keras.Sequential([
MaxPooling2D((2, 2)),
MaxPooling2D((2, 2)),
activation='relu'), Flatten(),
Dense(64, activation='relu'),
Dropout(dropout_rate),
Dense(10,
activation='softmax')
])
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
return model
best_accuracy = 0
best_model = None
# Hyperparameter tuning
for dr in dropout_rates:
print(f"Training model with learning rate = {lr} and dropout rate = {dr}")
best_accuracy = accuracy
best_model = model
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:7
TRANSFER LEARNING CONCEPT IN IMAGE
DATE :
CLASSIFICATION
AIM
To write a python program to implement a transfer learning concept in image classification
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applicationsimport MobileNetV2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.optimizers import Adam
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
base_model = MobileNetV2(weights='imagenet', include_top=False)
# Create a new model on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
model = keras.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(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
# Load and preprocess your dataset
# You can use your own dataset or a built-in datasetlike CIFAR-10
# Example of using CIFAR-10
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utilsimport to_categorical
(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)
# Use data augmentation for better performance
data_generator = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True
)
# Fine-tune the model
model.fit(data_generator.flow(x_train, y_train, batch_size=32), 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:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:8
PRE TRAINED MODEL ON KERAS FOR
DATE :
TRANSFER LEARNING
AIM
To write a python program to train a pre trained model on keras for transfer learning
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow.keras.applicationsimport VGG16
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Load the pre-trained VGG16 model without the top classification layers(include_top=False)
base_model = VGG16(weights='imagenet', include_top=False)
# Add custom classification layers on top of the pre-trained model
x = base_model.output
x = GlobalAveragePooling2D()(x) # Global average pooling layer
x = Dense(1024, activation='relu')(x) # Fully connected layer with 1024 units and ReLU
activation
predictions = Dense(NUM_CLASSES, activation='softmax')(x) # Output layer with softmax
activation for the number of
classes in your new task
# Create the final model
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model (optional)
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Load
and preprocess your dataset
# Example: Use ImageDataGenerator for loading and augmenting data
train_datagen = ImageDataGenerator(
rescale=1.0/255.0, # Normalize pixel values to the range [0, 1]
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
train_generator = train_datagen.flow_from_directory(
'path/to/train/dataset', # Path to the directory containing your training data
target_size=(224, 224), # Targetsize of the input images(depends on the inputsize expected by
VGG16)
batch_size=32,
class_mode='categorical' # Set to 'binary' for binary classification tasks
)
# Train the model
model.fit_generator(
train_generator,
steps_per_epoch=len(train_generator),
epochs=10 # Number of epochs for training (adjust as needed)
)
model.save('my_transfer_learning_model.h5')
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:9
DATE : SENTIMENT ANALYSIS USING RNN
AIM
To write a python program to perform sentiment analysis using RNN
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence
import pad_sequences from tensorflow.keras.models
import Sequential
from tensorflow.keras.layers import Embedding,
SimpleRNN, Dense from tensorflow.keras.optimizers
import Adam
# Load and preprocess the IMDb dataset
max_features = 10000 # Maximum number of words
in the vocabulary maxlen = 100 # Maximum
sequence length
batch_size = 32
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
x_train = pad_sequences(x_train,
maxlen=maxlen) x_test =
pad_sequences(x_test,
maxlen=maxlen) # Build the RNN
model
model = Sequential()
model.add(Embedding(max_
features, 32))
model.add(SimpleRNN(32))
model.add(Dense(1,
activation='sigmoid'))
model.compile(optimizer=Adam(lr=0.001),
loss='binary_crossentropy', metrics=['accuracy']) # Train the model
model.fit(x_train, y_train, epochs=5, batch_size=batch_size,
validation_split=0.2) # Evaluate the model
loss, accuracy =
model.evaluate(x_test, y_test)
print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:10
DATE : LSTM BASED AUTOENCORDER IN
TENSORFLOW/KERAS
AIM
To write a python program to implement an lstm based autoencorder in tensorflow/keras
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layersimportInput, LSTM, RepeatVector, TimeDistributed
from tensorflow.keras.models import Model
# Generate some sample data
input_data = np.array([[i/100.0 for i in range(100)]]) # Example inputsequence
input_data = np.reshape(input_data, (1, input_data.shape[1], 1)) # Reshape to
(batch_size,sequence_length,
input_dim)
# Define the LSTM-based autoencoder model
latent_dim = 32 # Dimension of the latent space
# Encoder
encoder_inputs = Input(shape=(None, 1))
encoder = LSTM(latent_dim,return_state=True)
encoder_outputs,state_h,state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]
# Decoder
decoder_inputs = Input(shape=(None, latent_dim))
decoder_lstm = LSTM(1, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states)
#Autoencoder
autoencoder = Model([encoder_inputs, decoder_inputs], decoder_outputs)
# Compile the model
autoencoder.compile(optimizer='adam', loss='mean_squared_error')
# Train the autoencoder
autoencoder.fit([input_data, np.zeros((1, input_data.shape[1], latent_dim))], input_data,
epochs=100, verbose=0)
# Use the trained autoencoder to encode and decode data
encoded_data = encoder.predict(input_data)
decoded_data = decoder_lstm.predict(encoded_data)
print("Original Data:")
print(input_data)
print("Encoded Data:")
print(encoded_data)
print("Decoded Data:")
print(decoded_data)
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:11
IMAGE GENERATION USING GAN
DATE :
AIM
To write a python program to perform image generation using gan
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import numpy as np
import matplotlib.pyplot
as plt import tensorflow
as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, LeakyReLU,
Reshape, Flatten from tensorflow.keras.optimizers import
Adam
# Define the generator
generator =
keras.Sequential([
Dense(128, input_shape=(100,),
activation='relu'), Dense(784,
activation='sigmoid'),
Reshape((28, 28))
])
# Define the discriminator
discriminator =
keras.Sequential([
Flatten(input_shape=(28,
28)), Dense(128,
activation='relu'),
Dense(1,
activation='sigmoid')
])
gan_input =
keras.Input(shape=(100,)) x =
generator(gan_input)
gan_output = discriminator(x)
gan = keras.Model(gan_input, gan_output)
gan.compile(loss='binary_crossentropy',
optimizer=Adam(0.0002, 0.5)) # Load the MNIST dataset
mnist = keras.datasets.mnist
(X_train, _), (_, _) =
mnist.load_data() X_train =
X_train / 127.5 - 1.0
X_train = np.expand_dims(X_train,
axis=-1) # Training the GAN
batch_size = 32
half_batch =
batch_size // 2 epochs =
10000
for epoch in range(epochs):
# Train the discriminator
idx = np.random.randint(0, X_train.shape[0],
half_batch) real_images = X_train[idx]
noise = np.random.normal(0, 1,
(half_batch, 100)) generated_images =
generator.predict(noise) real_labels =
np.ones((half_batch, 1))
fake_labels = np.zeros((half_batch, 1)) d_loss_real =
discriminator.train_on_batch(real_images, real_labels) d_loss_fake =
discriminator.train_on_batch(generated_images, fake_labels)
d_loss = 0.5 * np.add(d_loss_real,
d_loss_fake) # Train the generator
print(f"Epoch: {
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:12
CLASSIY A GIVEN IMAGE USING PRE
DATE : TRAINED MODEL
AIM
To write a python program to train a deep learning model to classiy a given image using pre
trained model
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't
already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python
3 as the default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to
start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left
corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it.
However, you can also manually save your work by clicking on File > Save or using the
shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applicationsimport MobileNetV2
from tensorflow.keras.modelsimport Model
from tensorflow.keras.layersimport 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:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:13
RECOMMENDATION SYSTEMS FROM SALES DATA USING
DATE : DEEP LEARNING
AIM
To write a python program for implementing recommendation systems from sales data using deep learning
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python 3 as the
default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it. However, you can also
manually save your work by clicking on File > Save or using the shortcut Ctrl + S..
PROGRAM
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applicationsimport MobileNetV2
from tensorflow.keras.modelsimport Model
from tensorflow.keras.layersimport 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:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:14
IMPLEMENT OBJECT DETECTION USING CNN
DATE :
AIM
To write a python program to implement object detection using cnn
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python 3 as the
default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it. However, you can also
manually save your work by clicking on File > Save or using the shortcut Ctrl + S..
PROGRAM
import numpy as np
import tensorflow as tf
from object_detection.utilsimportlabel_map_util, visualization_utils as vis_util
from PIL import Image
defrun_object_detection(image_path, model_path, label_map_path):
image = Image.open(image_path)
image_np = np.array(image)
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, 'rb') asfid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
category_index = label_map_util.create_category_index_from_labelmap(label_map_path,
use_display_name=True)
with detection_graph.as_default():
with tf.Session() assess:
ops = tf.get_default_graph().get_operations()
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
output_dict = sess.run(get_output_tensors(), feed_dict={image_tensor: image_np[None]})
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'][0],
output_dict['detection_classes'][0].astype(np.int64),
output_dict['detection_scores'][0],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=8)
return image_np
if name == ' main ':
image_path = 'path/to/image.jpg'
model_path = 'path/to/frozen_inference_graph.pb'
label_map_path = 'path/to/label_map.pbtxt'
result_image = run_object_detection(image_path, model_path, label_map_path)
# Display or save the result_image as needed
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified
Ex.No:15
DATE : SIMPLE REINFORCEMENT ALGORITHM FOR AN NLP
PROBLEM
AIM
To write a python program to implement any simple reinforcement algorithm for an nlp problem
1. Personal Computer
2. Colab notebook
PROCEDURE
1. Access google colab through the website. Sign in with your Google account if you haven't already.
2. Once you're signed in, you'll see an option to create a new notebook. Click on it.
3. After creating a new notebook, you'll be prompted to select a runtime. Colab offers Python 3 as the
default runtime.
4. In the notebook interface, you'll see a cell where you can input code. Click on the cell to start typing.
5. Write your Python code in the cell and Import the necessary python libraries
6. To execute the code, either press Shift + Enter or click on the play button at the top-left corner of the cell.
7. Colab automatically saves your notebook to your Google Drive as you work on it. However, you can also
manually save your work by clicking on File > Save or using the shortcut Ctrl + S..
PROGRAM
import random
# Define a simple environment with a chatbot
class ChatbotEnvironment:
def init (self):
self.state = "Hello, how can I assist you?"
self.conversation_history = []
self.reward = 0
def step(self, action):
# Simulate a user query
user_query = action
self.conversation_history.append((self.state, user_query))
# Simulate chatbot's response (you can replace this with a more advanced model)
if "help" in user_query:
self.state = "Sure, I can help you with that. What do you need?"
self.reward += 1
elif "thank you" in user_query:
self.state = "You're welcome! Let me know if you need anything else."
self.reward += 1
else:
self.state = "I'm sorry, I didn't understand. Can you rephrase your question?"
self.reward -= 1
return self.state, self.reward
# Define a simple Q-learning agent
class QLearningAgent:
def init (self, actions, learning_rate=0.1, discount_factor=0.9, exploration_prob=0.2):
self.actions = actions
self.learning_rate = learning_rate
self.discount_factor = discount_factor
self.exploration_prob = exploration_prob
self.q_table = {}
def
choose_action(self, state):
if random.uniform(0, 1) < self.exploration_prob:
return random.choice(self.actions)
else:
q_values = [self.q_table.get((state, a), 0) for a in self.actions]
return self.actions[q_values.index(max(q_values))]
def learn(self,state, action, reward, next_state):
current_q = self.q_table.get((state, action), 0)
best_next_q = max([self.q_table.get((next_state, a), 0) for a in self.actions])
updated_q = current_q + self.learning_rate * (reward + self.discount_factor * best_next_q - current_q)
self.q_table[(state, action)] = updated_q
# Train the chatbot using Q-learning
env = ChatbotEnvironment()
agent = QLearningAgent(actions=["ask", "thank"])
epochs = 1000
for _ in range(epochs):
state = env.state
action = agent.choose_action(state)
next_state, reward = env.step(action)
agent.learn(state, action,reward, next_state)
# Test the trained chatbot
state = env.state
print("Chatbot'sresponse:",state)
OUTPUT:
Mark Max Awarded
Allocation Marks
Preparation 2
Interest and 2
involvement
Skill in 4
completing
the
experiments
Viva-voice 2
Total 10
RESULT
Thus the Program is coded and the output has been successfully verified