0% found this document useful (0 votes)
61 views34 pages

DL Lab Manual

Uploaded by

aids2aitstpt
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)
61 views34 pages

DL Lab Manual

Uploaded by

aids2aitstpt
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
You are on page 1/ 34

Deep Learning Lab

To Run the Deep Learning Programs, you need to install below modules or
packages:

Before we can start using Jupyter Notebook, we need to install it on our


Windows machine. Here are the steps to follow:

1. First, you need to have Python installed on your machine. You can
download the latest version of Python from the official website
(https://www.python.org/downloads/). Make sure to select the option to
add Python to your system PATH during the installation process.
2. Once Python is installed, open the command prompt by pressing the
Windows key + R and typing cmd in the Run dialog box.
3. In the command prompt, type the following command to install Jupyter
Notebook:
4. pip install jupyter
This will download and install Jupyter Notebook and its dependencies.

5. After the installation is complete, type the following command to start


Jupyter Notebook:
6. jupyter notebook
This will open a new tab in your web browser with the Jupyter Notebook
interface.

Once you’ve created a new notebook, you can start writing code in the cells. To
run a cell, press Shift + Enter or click the Run button in the toolbar. You can
also add text, equations, and visualizations to your notebook using Markdown
syntax.
Jupyter Notebook also supports a variety of keyboard shortcuts to make your
work more efficient. Here are some of the most useful shortcuts:

• Shift + Enter: Run the current cell and move to the next one.
• Ctrl + Enter: Run the current cell.
• Esc: Enter command mode.
• Enter: Enter edit mode.
• A: Insert a new cell above the current cell.
• B: Insert a new cell below the current cell.
• D + D: Delete the current cell.
• M: Change the current cell type to Markdown.
• Y: Change the current cell type to code.

Install Below Libraries must and should:

In Cmd:

1) To upgrade Pip : python.exe -m pip install --upgrade pip


2) For Numpy : pip install numpy
3) For Pandas : pip install pandas
4) For Matplotlib : pip install matplotlib
5) For sklearn : pip install scikit-learn
6) For Pytorch : pip install torch
7) For Tensorflow : pip install tensorflow

To Run the DL programs It is mandatory to install all the above packages.


For Keras Package there is no need to install separately. It will be installed
under the package of tenserflow.
1. Aim: Installing Keras and Packages in Keras.
First, ensure you have Python installed on your system. Then, follow these steps:
Install Keras via pip:
pip install keras
This command will install Keras along with its dependencies.
Backend:
Keras relies on a backend engine to perform computations (such as TensorFlow
or Theano). If you don't have a backend installed, it's recommended to install
TensorFlow as Keras' default backend:
pip install tensorflow
Additional Packages:
Depending on your needs, you might require additional packages or specific
versions. For example, if you want to use a specific version of TensorFlow with
Keras, you can specify it during installation:
pip install tensorflow==x.x.x
# Replace x.x.x with the desired TensorFlow version
GPU Support:
If you have a compatible NVIDIA GPU and want to utilize it for faster
computations, you can install the GPU version of TensorFlow. Keep in mind that
this requires CUDA and cuDNN installed on your system:
pip install tensorflow-gpu
Verification:
After installation, you can verify that Keras is installed correctly by importing it
in a Python script or in a Python terminal:
import keras
If no errors occur, Keras is installed successfully and ready to use.
Remember, package versions may vary, so you might want to consult the Keras
documentation or specific package documentation for compatibility and version
details, especially if you have specific requirements or encounter compatibility
issues.
2. Aim: Setting up the Spyder ide environment and executing a
python program.
Setting up Spyder for Python programming is relatively straightforward. First,
ensure you have Python installed on your system. Spyder typically comes as part
of the Anaconda distribution, but it can also be installed separately via pip.
pip install spyder
Or install it using Anaconda:
If you have Anaconda installed, you can use the Anaconda Navigator to install
Spyder. Open Anaconda Navigator, go to the "Home" tab, and search for Spyder
in the list of available applications. Click the "Install" button next to Spyder to
install it.

Once Spyder is installed:


Launch Spyder: You can launch Spyder either from the command line by typing
spyder, or through the Anaconda Navigator if you installed it using Anaconda.
Create/Open a Python file: In the Spyder interface, you can create a new Python
file by clicking on "File" > "New File" or open an existing Python script by
clicking "File" > "Open".
Write your Python code: You can start writing your Python code in the editor
window.
Execute your code: To execute the code, you can either run the entire script or
execute specific sections of the code. Use the following methods:
Run entire script: Click on the green play button in the toolbar or use the keyboard
shortcut F5.

Run specific lines or selected code: Highlight the code you want to run and then
click the green play button or press F9.
Spyder provides a convenient interface with features like a variable explorer,
IPython console, debugger, and more, making it easier to write and debug Python
code.
Remember to have your Python environment properly set up and activated before
launching Spyder if you're using virtual environments to manage packages or
dependencies.
Spyder is a versatile and user-friendly IDE, allowing you to execute Python code
efficiently and debug your scripts seamlessly.
Certainly! First, let's install TensorFlow and some commonly used Python
libraries. Assuming you already have Python installed, here's how you can install
TensorFlow and a few additional libraries using pip.
Spyder link: https://www.spyder-ide.org/
Reference link: https://medium.com/@vertabeloacdm/how-to-install-the-
python-spyder-ide-and-run-scripts-ecfd31b37db6

3. Aim: Installing Tensorflow and Pytorch libraries and making


use of them.
TensorFlow Installation:
pip install tensorflow
This command installs the latest stable version of TensorFlow for CPU usage.
Pytorch Installation:
pip install torch
Additional Libraries:
Here are some popular Python libraries you might find useful:
1. NumPy:
pip install numpy
NumPy is fundamental for numerical computations in Python.

3. Matplotlib (for plotting):


pip install matplotlib
Matplotlib is a powerful plotting library.

4. Scikit-learn (for machine learning algorithms):


pip install scikit-learn
Scikit-learn provides various machine learning tools and algorithms.
Making Use of These Libraries:
Once installed, you can import and use these libraries in your Python code:

python
# Importing required libraries
import numpy as np
import pandas as pd
import tensorflow as tf

# Generate dummy data using NumPy


# Let's create 100 samples with 2 features and a label (0 or 1)
np.random.seed(0)
X = np.random.rand(100, 2) # 100 samples, 2 features
y = np.random.randint(2, size=100) # Binary labels

# Convert the NumPy arrays to a Pandas DataFrame for easier manipulation


df = pd.DataFrame({'Feature1': X[:, 0], 'Feature2': X[:, 1], 'Label': y})

# Display the first few rows of the DataFrame


print("DataFrame with dummy data:")
print(df.head())

# Build a simple neural network using TensorFlow


model = tf.keras.Sequential([
tf.keras.layers.Dense(3, activation='relu', input_shape=(2,)),
tf.keras.layers.Dense(1, activation='sigmoid')])

# Compile the model


model.compile(optimizer='adam',loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model using the dummy data
model.fit(X, y, epochs=5, verbose=0) # Training for 50 epochs

# Evaluate the model


loss, accuracy = model.evaluate(X, y)
print(f"\nModel Accuracy: {accuracy * 100:.2f}%")

# Predictions
predictions = model.predict(X[:5]) # Predicting on the first 5 samples
print("\nPredictions for the first 5 samples:")
print(predictions)

Output:

Note: For every run we get different values or predictions.


4. Aim: Train the model to add two numbers and report the result
using keras.
Description:
By using Keras, a high-level neural networks API, to train a model that can
perform a simple arithmetic operation: addition of two numbers. Specifically, the
model should take two numbers as input, perform the addition operation on them,
and then output the result. Once the model is trained, it should be capable of
predicting the sum of any two numbers it hasn't seen during the training phase.
This task serves as a basic demonstration of how neural networks can be trained
for mathematical operations using deep learning frameworks.
Source code:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(1, input_dim=2))
model.compile(optimizer='adam', loss='mean_squared_error')
# Example data
X = [[1, 2], [3, 4]]
y = [3, 7]
model.fit(X, y, epochs=10)
result = model.predict([[5, 6]])
print(result)
Output:

Note: For every run we get different values or predictions.


5. Aim: Train the model to Multiply two matrices and report the
result using keras.
Description:
By using Keras, a high-level neural networks API, to train a model for matrix
multiplication. Specifically, the model should take two matrices as input, perform
the multiplication operation between them, and then produce the resultant matrix
as the output. This task demonstrates how neural networks can be employed to
learn complex mathematical operations like matrix multiplication, highlighting
the versatility of deep learning frameworks in handling mathematical
computations.
Source code:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
X = np.array([[2, 3], [4, 5]])
y = np.array([[8], [20]])
model = Sequential()
model.add(Dense(1, input_dim=2, activation='linear'))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X, y, epochs=10)
result = model.predict([[6, 7]])
print(result)
Output:

Note: For every run we get different values or predictions.


6. Aim: Train the model to print the prime numbers using keras.
Description:
The objective would be to train a Keras model to recognize and predict prime
numbers. Given an input number, the model would output whether it is a prime
number or not. This task would involve creating a dataset of numbers and their
corresponding labels (prime or not prime) and then training a neural network to
learn the patterns associated with prime numbers.
Still, it's worth noting that traditional algorithms are more efficient for identifying
prime numbers, and using a neural network for this purpose would likely be
overcomplicating a simple task.
Source code:
# Importing required libraries
import numpy as np
from keras.models import Sequential
from keras.layers import Dense

def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(np.sqrt(n)) + 1):
if n % i == 0:
return False
return True

# Generate training data


X_train = np.random.randint(1, 100, size=(1000, 1)) # Random integers as input
y_train = np.array([is_prime(num) for num in X_train])
# Build the model
model = Sequential()
model.add(Dense(units=1, input_dim=1, activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
# Test the model
test_number = 45 # Replace with the number you want to check
prediction = model.predict(np.array([[test_number]]))
is_prime_prediction = prediction[0][0] > 0.5
print(f"The model predicts {test_number} is prime: {is_prime_prediction}")

Output:

Note: If the output is wrong, Run the program for several times to get the correct answer.
Because in each run it will be trained, then it predicts the correct output.
7. Recurrent Neural Networks
(a) Aim: Numpy implement of a simple recurrent neural network
Description:
RNN would consist of recurrent connections that allow the network to maintain
information in memory over time, making it suitable for sequential data tasks like
time series forecasting, natural language processing, and more. The
implementation would involve defining the architecture, initializing weights,
implementing the forward pass for computing predictions, and potentially a
backward pass for gradient computation if training is involved. This task aims to
provide a foundational understanding of how RNNs work under the hood by
building a simple version from scratch using NumPy for numerical computations.
Source code:
import numpy as np
# Define RNN parameters
input_size = 3
hidden_size = 4
output_size = 2
# Generate random input sequence
X = np.random.rand(5, input_size)

# Initialize weights
Wxh = np.random.rand(input_size, hidden_size)
Whh = np.random.rand(hidden_size, hidden_size)
Why = np.random.rand(hidden_size, output_size)

# Initialize hidden state


h_prev = np.zeros((1, hidden_size))
# Forward pass
for x in X:
h_next = np.tanh(np.dot(x, Wxh) + np.dot(h_prev, Whh))
y = np.dot(h_next, Why)
h_prev = h_next
print(y)

Output:

Note: For every run we get different values or predictions.

(b) Aim: Create a Recurrent Layer in keras


Description:
To create a recurrent layer in Keras by using SimpleRNN layer. Keras provides a
straightforward way to incorporate recurrent neural network (RNN) layers,
making it easier to build models for sequence data processing tasks like time
series forecasting or natural language processing.
Importing Necessary Modules: The code begins by importing essential modules
from Keras.
Model Definition: A sequential model is instantiated, which serves as a linear
stack of layers.
Adding SimpleRNN Layer: A SimpleRNN layer is added to the model with
specified parameters. Here, the layer consists of 64 units, and the input data is
expected to have a sequence length of 10 with each time step having 32 features.
Model Compilation: Before training, the model is compiled using the Adam
optimizer, mean squared error (MSE) as the loss function, and accuracy as the
metric for evaluation.
Model Summary: Finally, the model summary is printed, providing a detailed
overview of the architecture, including layer types, output shapes, and the number
of parameters.
Source code:
from keras.models import Sequential
from keras.layers import SimpleRNN
# Define the model
model = Sequential()
# Add a SimpleRNN layer
model.add(SimpleRNN(units=64, input_shape=(10, 32))) # 64 units, input
sequence length of 10, input feature dimension of 32
# You can continue building your model by adding more layers if needed
# For example, you might add Dense layers for classification or regression
tasks
# Compile the model (you need to compile before training)
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
# Print the model summary
model.summary()

Output:
(c) Aim: Prepare IMDB data for movie review classification
problem.
Description:
To train a simple recurrent neural network (RNN) model using Keras for the
IMDB movie review classification problem:
Data Preparation: The IMDB dataset is loaded and split into training and test
sets. Sequences are padded or truncated to have a consistent length of 500 tokens
to ensure uniform input dimensions.
Model Architecture: A sequential model is constructed in Keras with an
embedding layer to convert words into dense vectors. A SimpleRNN layer with
32 units is added to capture sequential dependencies. A Dense layer with a
sigmoid activation function is used for binary classification, predicting positive
or negative sentiment based on the reviews.
Model Compilation & Training: The model is compiled using the Adam
optimizer and binary cross-entropy loss. It's trained on the training data for 5
epochs with a batch size of 64, utilizing 20% of the data for validation.
Evaluation: After training, the model's performance is evaluated on the test set,
providing the accuracy metric to assess its classification performance on unseen
reviews.
Source code:
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Embedding, SimpleRNN, Dense
# Load the IMDB dataset
max_features = 5000 # Number of most frequent words to consider
max_len = 500 # Maximum sequence length
embedding_dim = 32 # Dimension of the embedding space
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# Pad sequences to ensure consistent length
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)

# Build the model


model = Sequential()

# Add an Embedding layer


model.add(Embedding(max_features, embedding_dim, input_length=max_len))

# Add a SimpleRNN layer


model.add(SimpleRNN(units=32))

# Add a Dense layer for binary classification (positive/negative sentiment)


model.add(Dense(units=1, activation='sigmoid'))

# 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=64, validation_split=0.2)

# Evaluate the model on the test set


loss, accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy * 100:.2f}%')
Output:

Note: For every run we get different values or predictions.

(d) Aim: Train the model with embedding and simple RNN layers.
Description:
To train a neural network model using an embedding layer followed by a simple
RNN layer for the IMDB movie review classification task:
Data Preparation: The IMDB dataset is loaded, considering the top 5,000 most
frequent words. Sequences are padded or truncated to a consistent length of 500
tokens for uniform input size.
Model Architecture: A sequential model is constructed in Keras, starting with an
embedding layer that converts words into dense vectors of 32 dimensions.A
Dense layer with a sigmoid activation function serves for binary classification,
distinguishing positive from negative sentiment.
Model Compilation & Training: The model is compiled using the Adam
optimizer and binary cross-entropy loss. Training is performed on the training
data for 5 epochs with a batch size of 64, utilizing 20% of the data for validation
to monitor performance.
Evaluation & Visualization: The trained model is evaluated on the test set to
measure its accuracy in sentiment classification. Additionally, the code visualizes
the training and validation accuracy across epochs using Matplotlib, providing
insights into the model's learning progress and potential overfitting tendencies.
Source code:
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Embedding, SimpleRNN, Dense
# Load the IMDB dataset
max_features = 10000 # Number of most frequent words to consider
max_len = 500 # Maximum sequence length
embedding_dim = 32 # Dimension of the embedding space
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# Pad sequences to ensure consistent length
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
# Build the model
model = Sequential()
# Add an Embedding layer
model.add(Embedding(max_features, embedding_dim, input_length=max_len))
# Add a SimpleRNN layer
model.add(SimpleRNN(units=32))
# Add a Dense layer for binary classification (positive/negative sentiment)
model.add(Dense(units=1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam',loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model
history=model.fit(x_train,y_train,epochs=5,batch_size=64, validation_split=0.2)
# Evaluate the model on the test set
loss, accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy * 100:.2f}%')
# Plot training and validation accuracy
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

Output:
(e) Aim: Plot the Results
Source code:
import matplotlib.pyplot as plt

# Train the model


history=model.fit(x_train,y_train,epochs=5,batch_size=64, validation_split=0.2)

# Plot training and validation accuracy


plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

# Plot training and validation loss


plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Show the plots
plt.tight_layout()
plt.show()

Output:
8. Aim: Consider temperature-forecast as one the example for
RNN and implement the following:
a) Inspect the data of the weather dataset
b) Parsing the data
c) Plotting the temperature timeseries
d) Plotting the first 10 days of the temperature timeseries
Description:
This program mainly focuses on analyzing and visualizing temperature forecast
data using Python's Pandas and Matplotlib libraries, specifically targeting tasks
related to time series data handling:
Data Inspection: The code begins by loading a weather dataset from a CSV file
path and displaying the first few rows to get a glimpse of the data structure. Basic
statistical information about the dataset, such as mean, standard deviation, etc., is
also presented to understand the data distribution.
Parsing the Data: The 'Date' column in the dataset is converted into a datetime
object, allowing for more intuitive time-based analysis and plotting.
Plotting the Temperature Timeseries: A plot is generated showcasing the
temperature timeseries, where the x-axis represents dates, and the y-axis displays
the corresponding temperatures over time.
Plotting the First 10 Days: A more focused visualization is created, zooming
into the first 10 days of temperature data to provide a clearer view of temperature
variations within this initial period.
Source Code: (your_dataset.csv)
import pandas as pd
import matplotlib.pyplot as plt
# a). Inspect the data
# Load the dataset (replace 'your_dataset.csv' with the actual file path)
df = pd.read_csv('your_dataset.csv')
# Display the first few rows of the dataset
print("Data Inspection:")
print(df.head())
# Display basic statistics of the dataset
print("\nDataset Statistics:")
print(df.describe())
# b). Parsing the data
# Assuming your dataset has a 'Date' column, parse it as a datetime object
df['Date'] = pd.to_datetime(df['Date'])

# c). Plotting the temperature timeseries


plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Temperature'])
plt.title('Temperature Timeseries')
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.show()

# d). Plotting the first 10 days of the temperature timeseries


plt.figure(figsize=(12, 6))
plt.plot(df['Date'][:10], df['Temperature'][:10], marker='o', linestyle='-')
plt.title('First 10 Days of Temperature Timeseries')
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.show()
Output:
9. Aim: Train a sentiment analysis model on IMDB dataset, use
RNN layers with LSTM/GRU notes.
Description:
The program demonstrates training a sentiment analysis model on the IMDB
dataset using recurrent neural network (RNN) layers with Long Short-Term
Memory (LSTM) units:
Data Preparation: The IMDB dataset is loaded, considering the top 10,000 most
frequent words, and sequences are padded or truncated to a consistent length of
200 tokens to maintain uniformity in input dimensions.
Model Architecture: A sequential model is constructed using Keras, starting with
an embedding layer that maps words to dense vectors of 32 dimensions. An
LSTM layer with 32 units is incorporated into the model. LSTM (Long Short-
Term Memory) is a type of RNN that helps in capturing long-term dependencies
in sequential data, making it suitable for tasks like sentiment analysis where the
context from earlier words can influence the sentiment of the entire sentence.
Model Compilation & Training: The model is compiled using the Adam
optimizer and binary cross-entropy loss, a suitable choice for binary classification
tasks. The model is trained on the training data for 5 epochs with a batch size of
64 and utilizing 20% of the data for validation to monitor and prevent overfitting.
Evaluation: After training, the model's performance is evaluated on the test set,
providing accuracy as a metric to assess its capability in classifying movie
reviews based on their sentiment.
Source Code:
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense
# Load the IMDB dataset
max_features = 10000 # Number of most frequent words to consider
max_len = 200 # Maximum sequence length
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)

# Pad sequences to ensure consistent length


x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)

# Build the model with LSTM layer


model = Sequential()

# Add an Embedding layer


model.add(Embedding(max_features, 32, input_length=max_len))

# Add an LSTM layer


model.add(LSTM(units=32))

# Add a Dense layer for binary classification (positive/negative sentiment)


model.add(Dense(units=1, activation='sigmoid'))

# 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=64, validation_split=0.2)
# Evaluate the model on the test set
loss, accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy * 100:.2f}%')
Output:

10. Convolutional Neural Networks


Aim: a) Preparing the IMDb data
b) Train and evaluate a simple 1D convent on IMDb Data

Source Code:

# 10a) Preparing the IMDB Data


from keras.datasets import imdb
from keras.preprocessing import sequence
max_features = 10000
maxlen = 500
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
#10b) Train and Evaluate a Simple 1D Convent on IMDB Data

from keras.models import Sequential


from keras.layers import Embedding, Conv1D, MaxPooling1D,
GlobalMaxPooling1D, Dense
model = Sequential()
model.add(Embedding(max_features, 128, input_length=maxlen))
model.add(Conv1D(32, 7, activation='relu'))
model.add(MaxPooling1D(5))
model.add(Conv1D(32, 7, activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
history = model.fit(x_train, y_train, epochs=3, batch_size=128,
validation_split=0.2)
# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Accuracy: {accuracy * 100:.2f}%")

Output:
c) Aim: Train and evaluate a simple 1D convent on temperature
prediction data.
Source Code:
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, MaxPooling1D,
GlobalMaxPooling1D, Dense
import numpy as np
# Generate synthetic temperature data
num_samples = 3000
sequence_length = 50
temperatures = np.random.randint(50, 100, num_samples)
data = []
labels = []
for i in range(len(temperatures) - sequence_length):
data.append(temperatures[i:i + sequence_length])
labels.append(temperatures[i + sequence_length])
data = np.array(data)
labels = np.array(labels)
# Split data into training and test sets
train_size = int(0.8 * len(data))
x_train, x_test = data[:train_size], data[train_size:]
y_train, y_test = labels[:train_size], labels[train_size:]
# Reshape data for Conv1D
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# Build the model
model = Sequential()
model.add(Conv1D(32, 5, activation='relu', input_shape=(sequence_length, 1)))
model.add(MaxPooling1D(3))
model.add(Conv1D(32, 5, activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.2)
# Evaluate the model
loss = model.evaluate(x_test, y_test)
print(f"Test Loss: {loss}")

Output:
11. Aim: Applying the Convolution Neural Network on computer
vision problems.
Description:

Source Code:
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Preprocess the data
x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)).astype('float32') / 255
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)).astype('float32') / 255
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# Build the CNN model
model_cnn_mnist = Sequential()
model_cnn_mnist.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28,
1)))
model_cnn_mnist.add(MaxPooling2D((2, 2)))
model_cnn_mnist.add(Conv2D(64, (3, 3), activation='relu'))
model_cnn_mnist.add(MaxPooling2D((2, 2)))
model_cnn_mnist.add(Conv2D(64, (3, 3), activation='relu'))
model_cnn_mnist.add(Flatten())
model_cnn_mnist.add(Dense(64, activation='relu'))
model_cnn_mnist.add(Dense(10, activation='softmax'))

# Compile the model


model_cnn_mnist.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model_cnn_mnist.fit(x_train,y_train,epochs=3,batch_size=64,validation_split=0
.2)
# Evaluate the model on the test set
loss, accuracy = model_cnn_mnist.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy * 100:.2f}%')

Output:
12. Aim: Image Classification on MNIST dataset (CNN model with
Fully connected layer)
Description:

Source Code:
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Preprocess the data
x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)).astype('float32') / 255
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)).astype('float32') / 255
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# Build the CNN model with fully connected layer
model_cnn_mnist = Sequential()
model_cnn_mnist.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28,
1)))
model_cnn_mnist.add(MaxPooling2D((2, 2)))
model_cnn_mnist.add(Conv2D(64, (3, 3), activation='relu'))
model_cnn_mnist.add(MaxPooling2D((2, 2)))
model_cnn_mnist.add(Conv2D(64, (3, 3), activation='relu'))
model_cnn_mnist.add(Flatten())
# Fully connected layer
model_cnn_mnist.add(Dense(64, activation='relu'))

# Output layer
model_cnn_mnist.add(Dense(10, activation='softmax'))
# Compile the model
model_cnn_mnist.compile(optimizer='adam',loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model_cnn_mnist.fit(x_train,y_train,epochs=3,batch_size=64,validation_split=0
.2)
# Evaluate the model on the test set
loss, accuracy = model_cnn_mnist.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy * 100:.2f}%')

Output:

You might also like