0% found this document useful (0 votes)
13 views23 pages

Deep Learning Laboratory Manual

The document is a laboratory manual for a Deep Learning course in the Computer Science Engineering department at KG Reddy College for the academic year 2023-2024. It outlines the institution's vision and mission, program educational objectives, program outcomes, and specific outcomes for graduates, as well as course objectives and outcomes related to deep learning. Additionally, it provides a list of experiments and detailed instructions for setting up environments and implementing deep learning models using various libraries.

Uploaded by

josebubyjose
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)
13 views23 pages

Deep Learning Laboratory Manual

The document is a laboratory manual for a Deep Learning course in the Computer Science Engineering department at KG Reddy College for the academic year 2023-2024. It outlines the institution's vision and mission, program educational objectives, program outcomes, and specific outcomes for graduates, as well as course objectives and outcomes related to deep learning. Additionally, it provides a list of experiments and detailed instructions for setting up environments and implementing deep learning models using various libraries.

Uploaded by

josebubyjose
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/ 23

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

DEEP LEARNING LABORATORY MANUAL

Subject Code : KGR2358113


Regulation : KGR23

Academic Year : 2023-2024

M .Tech CSE/CS I Year / I Sem

COMPUTER SCIENCE AND ENGINEERING


KG REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
Affiliated o JNTUH, Chilkur,(V), Moinabad(M) R. R Dist, TS-501504
VISION AND MISSION OF THE INSTITUTION
VISION:

To become an institution which is internationally recognized for its holistic approach to


engineering, innovative teaching and learning culture, research and entrepreneurial ecosystem,
and sustainable social impact in the community.

MISSION:

• To offer undergraduate and post-graduate programs which are supported through industry
relevant curriculum and innovative teaching and learning processes that would help students succeed in
their professional careers.
• To provide faculty and students with an ecosystem that fosters innovation, research,
entrepreneurship, and international exposure through strategic partnerships with governmentorganizations
and collaboration with industries.
• To provide holistic learning environment to students which will contribute to their personal and
professional growth and enable them to become leaders in their respective fields.

• To contribute to the development of the region by using our technological expertise to work with
nearby communities and support them in their social and economic development.

\
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION:
To be recognized as a department of excellence by stimulating a learning environment in
which students and faculty will thrive and grow to achieve their professional, institutional and
societal goals.

MISSION:
• To provide high quality technical education to students that will enable life-long learning and
build expertise in advanced technologies in Computer Science and Engineering.

• To promote research and development by providing opportunities to solve complex engineering


problems in collaboration with industry and government agencies.

• To encourage professional development of students that will inculcate ethical values and
leadership skills through entrepreneurship while working with the community to address societalissues.

PROGRAM EDUCATIONAL OBJECTIVES


PEO 1: Graduates will provide solutions to difficult and challenging issues in their profession
by applying computer science and engineering theory and principles.
PEO 2: Graduates have successful careers in computer science and engineering fields or will
be able to successfully pursue advanced degrees.
PEO 3: Graduates will communicate effectively, work collaboratively and exhibit high levels
of professionalism, moral and ethical responsibility.
PEO 4: Graduates will develop the ability to understand and analyze engineering issues in a
broader perspective with ethical responsibility towards sustainable development.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PROGRAM OUTCOMES

PO I: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.

PO II: Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.

PO III: Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and safety,
and the cultural, societal, and environmental considerations.
PO IV: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.
PO V: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT
tools including prediction and modeling to complex engineering activities with an understanding of the limitations.
PO VI: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health,
safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
PO VII: Environment and sustainability: Understand the impact of the professional engineering solutions in societal
and environmental contexts, and demonstrate the knowledge of and need for sustainable development.
PO VIII: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO IX: Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams,
and in multidisciplinary settings.
PO X: Communication: Communicate effectively on complex engineering activities with the engineering community
and with society at large, such as, being able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.
PO XI: Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
PO XII: Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM SPECIFIC OUTCOMES

PSO1: The Computer Science and Engineering graduates are able to analyze, design, develop, test
and apply management principles, mathematical foundations in the development of intelligent
systems with computational solutions, make them to expert in designing the secure application
and hardware prototype
PSO2: The graduating student will be analyze the contemporary research issues in different areasof
computer science & engineering and explore research gaps, analyze and carry out research in
the specialized/emerging areas.
PSO3: Develop their skills to solve problems in the broad area of programming concepts and
appraise environmental and social issues with ethics and manage different projects in multi-
disciplinary field to conducive in cultivating skills for successful career, entrepreneurship and
higher studies.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Course Objectives:

1. To Build The Foundation Of Deep Learning.

2. To Understand How To Build The Neural Network.

3. To enable students to develop successful machine learning concepts.

Course Outcomes:

CO1: Upon the Successful Completion of the Course, the Students would be able to

CO2: Learn The Fundamental Principles Of Deep Learning.

CO3: Identify The Deep Learning Algorithms For Various Types of Learning Tasks in
various domains.

CO4: Implement Deep Learning Algorithms And Solve Real-world problems.


S.NO LIST OF EXPERIMENTS:

Setting up the Spyder IDE Environment and Executing a Python Program


1
Installing Keras, Tensorflow and Pytorch libraries and making use of them
2
Applying the Convolution Neural Network on computer vision problems
3
Image classification on MNIS T dataset (CNN model with Fully connected layer)
4
Applying the Deep Learning Models in the field of Natural Language Processing
5
Train a sentiment analysis model on IMDB dataset, use RNN layers with

LSTM/GRU notes
6
Applying the Auto encoder algorithms for encoding the real-world data
7
Applying Generative Adversial Networks for image generation and unsupervised

tasks.
8
1. Setting up the Spyder IDE Environment and Executing a Python Program

To set up Spyder IDE environment and execute a Python program, follow these steps:

1. Install Anaconda: Spyder is included in Anaconda, so you will need to install Anaconda to
use Spyder. You can download Anaconda from the Anaconda website:
https://www.anaconda.com/products/distribution.
2. Open Spyder: Once you have installed Anaconda, open Spyder by searching for it in your
operating system's search bar.
3. Create a new file: To create a new Python file, click on "File" in the top menu bar, then
"New File". Alternatively, you can use the keyboard shortcut "Ctrl+N".
4. Write your Python code: Write your Python code in the editor window that opens. For
example, you can write a simple "Hello, World!" program like this:

Print ("Hello, World!")

5. Save your file: To save your Python file, click on "File" in the top menu bar, then "Save".
Alternatively, you can use the keyboard shortcut "Ctrl+S". Choose a name for your file and save it
in a location that you can easily find later.
6. Execute your Python program: To execute your Python program, click on the green "Run"
button in the toolbar at the top of the Spyder window. Alternatively, you can use the keyboard
shortcut "F5". Your program's output will appear in the console at the bottom of the Spyder
window.
2. Installing Keras, Tensorflow and Pytorch libraries and making use of them

To install Keras, TensorFlow, and PyTorch libraries and make use of them, follow these
steps:

1. Install Anaconda: Keras, TensorFlow, and PyTorch can all be installed through the
Anaconda distribution, which can be downloaded from the Anaconda website:
https://www.anaconda.com/products/distribution.
2. Open Anaconda Navigator: Once you have installed Anaconda, open the Anaconda
Navigator by searching for it in your operating system's search bar.
3. Create a new environment: To create a new environment, click on the "Environments" tab
in the left sidebar of the Anaconda Navigator, then click on the "Create" button at the
bottom of the window. Choose a name for your environment and select the Python
version that you want to use.
4. Install Keras, TensorFlow, and PyTorch: In the new environment that you just created,
click on the "Not Installed" dropdown menu and select "All". Then, search for "Keras",
"TensorFlow", and "PyTorch" in the search bar, and click on the checkboxes next to each
library. Finally, click on the "Apply" button at the bottom of the window to install the
libraries.
5. Open Spyder: Once you have installed Keras, TensorFlow, and PyTorch, open Spyder by
clicking on the "Launch" button next to your new environment in the Anaconda Navigator.
6. Import the libraries: In your Python code, import the Keras, TensorFlow, and PyTorch
libraries like this:

import keras import tensorflow as tf import torch

7. Use the libraries: You can now use the Keras, TensorFlow, and PyTorch libraries in your
code to build and train neural networks. Here's an example of how to create a simple neural
network using Keras:

from keras.models import Sequential from keras.layers import Dense model =

Sequential() model.add(Dense(10, activation='relu', input_shape=(784,)))

model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam',

metrics=['accuracy'])
This code defines a neural network with one hidden layer of 10 neurons, an input shape of 784
(which corresponds to 28x28 pixel images), and an output layer of 10 neurons (corresponding to
the 10 possible digits in MNIST). The "compile" method specifies the loss function, optimizer,
and evaluation metrics for training the model.

3. Applying the Convolution Neural Network on computer vision problems

Convolutional Neural Networks (CNNs) are a popular type of deep learning model used in
computer vision problems. Here are the steps to apply a CNN to a computer vision problem:

Prepare the data: The first step in any computer vision problem is to prepare the data. This
involves collecting and labeling a dataset of images, and then splitting the dataset into training
and validation sets. The images should be resized and normalized to a consistent size and
format.

Define the model: Once the data is prepared, you can define the CNN model in your code. A
typical CNN architecture for image classification consists of convolutional layers, pooling layers,
and fully connected layers. You can use a library like Keras, TensorFlow, or PyTorch to define the
model.

Train the model: After defining the model, you need to train it on the training set. This involves
feeding the images through the CNN and adjusting the weights of the model to minimize the
loss function. You can use techniques like stochastic gradient descent, batch normalization, and
data augmentation to improve the training process.

Evaluate the model: Once the model is trained, you need to evaluate its performance on the
validation set. This involves feeding the validation images through the CNN and calculating
metrics like accuracy, precision, and recall.

Tune the hyperparameters: If the model's performance on the validation set is not satisfactory,
you can tune the hyperparameters of the model. Hyperparameters include things like the
learning rate, batch size, and number of layers in the CNN. You can use techniques like grid
search or random search to find the optimal hyperparameters for your problem.

Test the model: After tuning the hyperparameters, you should test the model on a separate test
set to get an unbiased estimate of its performance. This involves feeding the test images
through the CNN and calculating metrics like accuracy, precision, and recall.

Deploy the model: Finally, if the model's performance is satisfactory, you can deploy it to make
predictions on new, unseen images. This involves saving the trained model weights to disk and
loading them into a production environment, where new images can be fed through the CNN and
classified.

4. Image classification on MNIST dataset (CNN model with Fully connected layer)

Convolutional Neural Network (CNN) with a fully connected layer for image classification
on the MNIST dataset using Keras:

1. Import the necessary libraries:

import numpy as np import tensorflow as tf from tensorflow import keras


fromtensorflow.keras import layers

2. Load the MNIST dataset:

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

3. Preprocess the data:

x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0 x_test =


x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0 y_train =
keras.utils.to_categorical(y_train) y_test = keras.utils.to_categorical(y_test)

This code rescales the pixel values of the images to be between 0 and 1, and one-hot encodes
the labels.

4. Define the model:

model = keras.Sequential( [ keras.Input(shape=(28, 28, 1)), layers.Conv2D(32,


kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(10,
activation="softmax"), ] ) model.summary()

This code defines a CNN model with two convolutional layers, each followed by a max pooling
layer. The flattened output is then passed through a fully connected layer with a softmax
activation function, which outputs probabilities for each class.

5. Compile and train the model:

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])


model.fit(x_train, y_train, batch_size=128, epochs=5, validation_split=0.1)
This code compiles the model using categorical cross-entropy as the loss function, the Adam
optimizer, and accuracy as the evaluation metric. It then trains the model on the training set for
5 epochs, with a batch size of 128 and a validation split of 0.1.
6. Evaluate the model:
test_loss, test_acc = model.evaluate(x_test, y_test) print("Test accuracy:", test_acc)

This code evaluates the model on the test set and prints the accuracy.

By following these steps, you can create and train a CNN model with a fully connected layer for
image classification on the MNIST dataset using Keras.

5. Applying the Deep Learning Models in the field of Natural Language Processing

Deep learning models have achieved remarkable success in Natural Language Processing (NLP)
tasks such as language translation, sentiment analysis, and text classification. Here are some
examples of deep learning models used in NLP:

Recurrent Neural Networks (RNNs): RNNs are a type of deep learning model used for sequential
data such as text. They are particularly useful for tasks such as language modeling and machine
translation. RNNs have the ability to capture the context of a word based on the previous words
in a sentence.

Long Short-Term Memory (LSTM): LSTMs are a type of RNN that can learn long-term
dependencies in sequential data. They are particularly useful for tasks such as sentiment
analysis and language translation.
Convolutional Neural Networks (CNNs): CNNs are a type of deep learning model used for tasks
such as text classification and sentiment analysis. They are particularly useful for tasks that
involve feature extraction from input data.

Transformers: Transformers are a type of deep learning model that are particularly useful for
tasks such as language translation and question answering. They use self-attention
mechanisms to focus on relevant parts of the input sequence.

Here are the steps to apply a deep learning model in NLP:

Prepare the data: The first step is to prepare the data for the specific NLP task. This involves
collecting and cleaning the data, and then converting it into a format that can be fed into a deep
learning model.

Preprocess the data: The next step is to preprocess the data, which involves converting text into
numerical representations that can be fed into a deep learning model. This can involve
techniques such as tokenization, stemming, and lemmatization.

Define the model: Once the data is preprocessed, you can define the deep learning model. This
involves selecting the appropriate architecture for the task at hand and configuring the model
hyperparameters.

Train the model: After defining the model, you need to train it on the training set. This involves
feeding the input data through the deep learning model and adjusting the weights of the model
to minimize the loss function.

Evaluate the model: Once the model is trained, you need to evaluate its performance on the
validation set. This involves feeding the validation data through the deep learning model and
calculating metrics such as accuracy and F1 score.

Test the model: After evaluating the model on the validation set, you should test the model on a
separate test set to get an unbiased estimate of its performance.

Deploy the model: Finally, if the model's performance is satisfactory, you can deploy it to make
predictions on new, unseen text data. This involves saving the trained model weights to disk and
loading them into a production environment, where new text data can be fed through the model
and classified.

6. Train a sentiment analysis model on IMDB dataset, use RNN layers with LSTM/GRU notes
Load the IMDB dataset: The first step is to load the IMDB dataset, which contains movie
reviews labeled as positive or negative.

Preprocess the data: Preprocess the text by removing stop words, special characters, and
converting them into lowercase. Tokenize the text data into sequences of integers, and pad the
sequences to a fixed length.

Split the data: Split the preprocessed data into training and testing sets.

Build the model: Build a sequential model in Keras, with an Embedding layer that will learn word
embeddings from the data, followed by a RNN layer with LSTM/GRU nodes, and a dense layer
with a sigmoid activation function that will output the sentiment probability.

Compile the model: Compile the model with binary cross-entropy as the loss function and Adam
optimizer.

Train the model: Train the model on the training set, and validate it on the testing set. You can
also use early stopping to prevent overfitting.

Evaluate the model: Evaluate the model on the testing set using metrics such as accuracy,
precision, recall, and F1 score.

Make predictions: Use the trained model to make predictions on new text data.

Here is some sample code that can be used to train the sentiment analysis model on the IMDB
dataset:

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, LSTM, GRU, Dense

from tensorflow.keras.callbacks import EarlyStopping

# Load the IMDB dataset

vocab_size = 10000
max_length = 500

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)

# Preprocess the data

x_train = pad_sequences(x_train, maxlen=max_length)

x_test = pad_sequences(x_test, maxlen=max_length)

# Build the model

model = Sequential()

model.add(Embedding(vocab_size, 128, input_length=max_length))

model.add(LSTM(128))

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

# Compile the model

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the model

early_stop = EarlyStopping(monitor='val_loss', patience=2)

model.fit(x_train, y_train, epochs=10, batch_size=128, validation_data=(x_test, y_test),


callbacks=[early_stop])

# Evaluate the model

loss, accuracy = model.evaluate(x_test, y_test)


print('Test Accuracy: {}'.format(accuracy))

# Make predictions on new data

new_reviews = ['I loved this movie!', 'I hated this movie.']

new_reviews = [tf.keras.preprocessing.text.text_to_word_sequence(review) for review in


new_reviews]

new_reviews = tf.keras.preprocessing.sequence.pad_sequences(new_reviews,
maxlen=max_length)

print(model.predict(new_reviews))

In this example, we use the LSTM layer for the RNN architecture, but you can replace it with the
GRU layer by changing the line model.add(LSTM(128)) to model.add(GRU(128)).

7. Applying the Autoencoder algorithms for encoding the real-world data

Autoencoders are a class of neural network algorithms that can be used for unsupervised
learning. The idea is to train a neural network to reconstruct the input data with a
bottleneck layer that can learn to extract the essential features of the data. In other
words, the network is trained to encode the input data into a compressed representation
and then decode it back to the original form.

Autoencoders have a wide range of applications, including data compression, denoising,


and anomaly detection. Here are the steps to apply autoencoder algorithms for encoding
real-world data:

Load and preprocess the data: Load the data into memory and preprocess it as needed.
This could include normalizing the data, removing outliers, or converting it into a suitable
format for input into the autoencoder.

Split the data: Split the data into training and testing sets.

Build the autoencoder model: Build a neural network model with an encoder and decoder
part. The encoder part will compress the input data into a latent representation, while the
decoder part will reconstruct the input data from the latent representation.
Compile the model: Compile the model with a suitable loss function, such as mean
squared error (MSE) or binary cross-entropy, and an optimizer.

Train the model: Train the model on the training set, using the compiled loss function and
optimizer.

Evaluate the model: Evaluate the model on the testing set, using metrics such as MSE or
binary cross-entropy.

Use the model for encoding: Once the autoencoder model is trained, you can use the
encoder part of the model to encode new data into a compressed representation.

Here is some sample code that can be used to apply an autoencoder algorithm for
encoding real-world data:

import numpy as np

from tensorflow.keras.layers import Input, Dense

from tensorflow.keras.models import Model

# Load and preprocess the data

data = np.random.normal(0, 1, size=(1000, 100)) # Example data

data = (data - np.mean(data)) / np.std(data) # Normalize the data

# Split the data

train_data = data[:800]

test_data = data[800:]

# Build the autoencoder model

input_dim = data.shape[1]

encoding_dim = 32
input_layer = Input(shape=(input_dim,))

encoder_layer = Dense(encoding_dim, activation='relu')(input_layer)

decoder_layer = Dense(input_dim, activation='linear')(encoder_layer)

autoencoder = Model(inputs=input_layer, outputs=decoder_layer)

# Compile the model

autoencoder.compile(optimizer='adam', loss='mse')

# Train the model

autoencoder.fit(train_data, train_data, epochs=50, batch_size=32,


validation_data=(test_data, test_data))

# Evaluate the model

mse = autoencoder.evaluate(test_data, test_data)

print('Test MSE: {:.2f}'.format(mse))

# Use the model for encoding

encoder = Model(inputs=input_layer, outputs=encoder_layer)

compressed_data = encoder.predict(data)

In this example, we use a simple fully-connected neural network architecture for the
autoencoder. The input data is normalized, and the encoder and decoder parts of the
model are defined using the Keras functional API. We compile the model with the MSE
loss function and the Adam optimizer and train it on the training set. Finally, we evaluate
the model on the testing set and use the encoder part of the model to encode the input
data into a compressed representation.
8. Applying Generative Adversial Networks for image generation and unsupervised tasks.

Generative Adversarial Networks (GANs) are a class of neural network algorithms that are
used for unsupervised learning tasks, particularly for image generation. GANs consist of two
neural networks: a generator network and a discriminator network. The generator network is
trained to generate images that are similar to the training data, while the discriminator network
is trained to distinguish between the generated images and the real images.

Here are the steps to apply GANs for image generation and unsupervised tasks:

Load and preprocess the data: Load the data into memory and preprocess it as needed. This
could include resizing the images, normalizing the pixel values, or converting them into a
suitable format for input into the GAN.

Build the generator network: Build a neural network model that takes a random noise vector as
input and generates an image. This could be done using a convolutional neural network (CNN)
architecture.

Build the discriminator network: Build a neural network model that takes an image as input and
outputs a probability value that indicates whether the input is real or generated by the generator
network.

Build the GAN model: Combine the generator and discriminator networks to form the GAN
model. The generator network is trained to fool the discriminator network into believing that the
generated images are real, while the discriminator network is trained to distinguish between the
real and generated images.

Compile the GAN model: Compile the GAN model with a suitable loss function, such as binary
cross-entropy, and an optimizer.

Train the GAN model: Train the GAN model by alternating between training the generator and
discriminator networks. The generator network is trained to generate images that fool the
discriminator network, while the discriminator network is trained to distinguish between the real
and generated images.

Generate new images: Once the GAN model is trained, you can use the generator network to
generate new images by feeding in random noise vectors as input.

Here is some sample code that can be used to apply GANs for image generation and
unsupervised tasks:
import numpy as np

from tensorflow.keras.layers import Input, Dense, Reshape, Flatten

from tensorflow.keras.layers import Conv2D, Conv2DTranspose

from tensorflow.keras.models import Model

from tensorflow.keras.optimizers import Adam

# Load and preprocess the data

data = np.random.normal(0, 1, size=(1000, 28, 28, 1)) # Example data

data = (data - np.mean(data)) / np.std(data) # Normalize the data

# Build the generator network

latent_dim = 100

generator_input = Input(shape=(latent_dim,))

generator_layer = Dense(7 * 7 * 64, activation='relu')(generator_input)

generator_layer = Reshape((7, 7, 64))(generator_layer)

generator_layer = Conv2DTranspose(64, (3, 3), strides=(2, 2), padding='same',


activation='relu')(generator_layer)

generator_layer = Conv2DTranspose(32, (3, 3), strides=(2, 2), padding='same',


activation='relu')(generator_layer)

generator_layer = Conv2DTranspose(1, (3, 3), strides=(1, 1), padding='same',


activation='tanh')(generator_layer)

generator = Model(inputs=generator_input, outputs=generator_layer)

# Build the discriminator network


discriminator_input = Input(shape=(28, 28, 1))

discriminator_layer = Conv2D(32, (3, 3), strides=(2, 2), padding='same',


activation='relu')(discriminator_input)

discriminator_layer = Conv2D(64, (3, 3),

strides=(2, 2), padding='same', activation='relu')(discriminator_layer)

discriminator_layer = Flatten()(discriminator_layer)

discriminator_layer = Dense(1, activation='sigmoid')(discriminator_layer)

discriminator = Model(inputs=discriminator_input, outputs=discriminator_layer)

Build the GAN model

discriminator.trainable = False

gan_input = Input(shape=(latent_dim,))

gan_layer = generator(gan_input)

gan_output = discriminator(gan_layer)

gan = Model(inputs=gan_input, outputs=gan_output)

Compile the GAN model

gan.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5))

Train the GAN model


batch_size = 32

epochs = 10000

for epoch in range(epochs):

# Generate random noise vectors as input to the generator network

noise = np.random.normal(0, 1, size=(batch_size, latent_dim)

# Generate fake images using the generator network

fake_images = generator.predict(noise)

# Combine the real and fake images into a single array

real_images = data[np.random.randint(0, data.shape[0], size=batch_size)]

images = np.concatenate([real_images, fake_images])

# Create labels for the real and fake images

real_labels = np.ones((batch_size, 1))

fake_labels = np.zeros((batch_size, 1))

labels = np.concatenate([real_labels, fake_labels])

# Train the discriminator network

discriminator_loss = discriminator.train_on_batch(images, labels)

# Train the generator network

noise = np.random.normal(0, 1, size=(batch_size, latent_dim))


generator_loss = gan.train_on_batch(noise, real_labels)

# Print the loss values every 100 epochs

if epoch % 100 == 0:

print(f'Epoch {epoch}, Discriminator Loss: {discriminator_loss}, Generator Loss:


{generator_loss}')

Generate new images

noise = np.random.normal(0, 1, size=(10, latent_dim))

generated_images = generator.predict(noise)

In this example, we are using a simple generator and discriminator network architecture with a
latent dimension of 100. The generator network takes a random noise vector as input and
generates an image, while the discriminator network takes an image as input and outputs a
probability value that indicates whether the input is real or generated by the generator network.

We then combine the generator and discriminator networks to form the GAN model and compile
it with a suitable loss function and optimizer. We train the GAN model by alternating between
training the generator and discriminator networks, and we generate new images using the
trained generator network.

You might also like