SlideShare a Scribd company logo
1 of 15
Download to read offline
Need an detailed analysis of what this code/model is doing. Thanks
#Step 1: Import the required Python libraries:
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
from keras.optimizers import Adam,SGD
from keras.datasets import cifar10
#Step 2: Load the data.
#Loading the CIFAR10 data
(X, y), (_, _) = keras.datasets.cifar10.load_data()
#Selecting a single class of images
#The number was randomly chosen and any number
#between 1 and 10 can be chosen
X = X[y.flatten() == 8]
#Step 3: Define parameters to be used in later processes.
#Defining the Input shape
image_shape = (32, 32, 3)
latent_dimensions = 100
#Step 4: Define a utility function to build the generator.
def build_generator():
model = Sequential()
#Building the input layer
model.add(Dense(128 * 8 * 8, activation="relu",
input_dim=latent_dimensions))
model.add(Reshape((8, 8, 128)))
model.add(UpSampling2D())
model.add(Conv2D(128, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.78))
model.add(Activation("relu"))
model.add(UpSampling2D())
model.add(Conv2D(64, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.78))
model.add(Activation("relu"))
model.add(Conv2D(3, kernel_size=3, padding="same"))
model.add(Activation("tanh"))
#Generating the output image
noise = Input(shape=(latent_dimensions,))
image = model(noise)
return Model(noise, image)
#Step 5: Define a utility function to build the discriminator.
def build_discriminator():
#Building the convolutional layers
#to classify whether an image is real or fake
model = Sequential()
model.add(Conv2D(32, kernel_size=3, strides=2,
input_shape=image_shape, padding="same"))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size=3, strides=2, padding="same"))
model.add(ZeroPadding2D(padding=((0,1),(0,1))))
model.add(BatchNormalization(momentum=0.82))
model.add(LeakyReLU(alpha=0.25))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization(momentum=0.82))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(256, kernel_size=3, strides=1, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.25))
model.add(Dropout(0.25))
#Building the output layer
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
image = Input(shape=image_shape)
validity = model(image)
return Model(image, validity)
#Step 6: Define a utility function to display the generated images.
def display_images():
# Generate a batch of random noise
noise = np.random.normal(0, 1, (16, latent_dimensions))
# Generate images from the noise
generated_images = generator.predict(noise)
# Rescale the images to 0-1 range
generated_images = 0.5 * generated_images + 0.5
# Plot the generated images
plt.figure(figsize=(6, 6))
for i in range(generated_images.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(generated_images[i])
plt.axis('off')
plt.tight_layout()
plt.show()
plt.close()
#Step 7: Build the GAN.
# Building and compiling the discriminator
discriminator = build_discriminator()
discriminator.compile(loss='binary_crossentropy',
optimizer=Adam(0.0002,0.5),
metrics=['accuracy'])
#Making the discriminator untrainable
#so that the generator can learn from fixed gradient
discriminator.trainable = False
# Building the generator
generator = build_generator()
#Defining the input for the generator
#and generating the images
z = Input(shape=(latent_dimensions,))
image = generator(z)
#Checking the validity of the generated image
valid = discriminator(image)
#Defining the combined model of the generator and the discriminator
combined_network = Model(z, valid)
combined_network.compile(loss='binary_crossentropy',
optimizer=Adam(0.0002,0.5))
#Step 8: Train the network.
num_epochs=15000
batch_size=32
display_interval=1000
losses=[]
#Normalizing the input
X = (X / 127.5) - 1.
#Defining the Adversarial ground truths
valid = np.ones((batch_size, 1))
#Adding some noise
valid += 0.05 * np.random.random(valid.shape)
fake = np.zeros((batch_size, 1))
fake += 0.05 * np.random.random(fake.shape)
for epoch in range(num_epochs):
#Training the Discriminator
#Sampling a random half of images
index = np.random.randint(0, X.shape[0], batch_size)
images = X[index]
#Sampling noise and generating a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dimensions))
generated_images = generator.predict(noise)
#Training the discriminator to detect more accurately
#whether a generated image is real or fake
discm_loss_real = discriminator.train_on_batch(images, valid)
discm_loss_fake = discriminator.train_on_batch(generated_images, fake)
discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake)
#Training the Generator
#Sampling noise and generating a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dimensions))
misleading_targets = np.ones((batch_size, 1))
#Training the generator to generate images
#that pass the authenticity test
genr_loss = combined_network.train_on_batch(noise, misleading_targets)
# Display generated images at the end of every 1000th epoch
#Tracking the progress
if epoch % display_interval == 0:
display_images()
noise = np.random.normal(0, 1, (16, latent_dimensions))
generated_images = generator.predict(noise)
generated_images = 0.5 * generated_images + 0.5
plt.figure(figsize=(6, 6))
for i in range(generated_images.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(generated_images[i])
plt.axis('off')
plt.tight_layout()
plt.savefig(f"epoch_{epoch+1}.png")
plt.close()
#Printing the progress and losses of the current epoch
print(f"Epoch {epoch} Discriminator Loss: {discm_loss[0]} Generator Loss: {genr_loss}")
#Step 1: Import the required Python libraries:
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
from keras.optimizers import Adam,SGD
from keras.datasets import cifar10
#Step 2: Load the data.
#Loading the CIFAR10 data
(X, y), (_, _) = keras.datasets.cifar10.load_data()
#Selecting a single class of images
#The number was randomly chosen and any number
#between 1 and 10 can be chosen
X = X[y.flatten() == 8]
#Step 3: Define parameters to be used in later processes.
#Defining the Input shape
image_shape = (32, 32, 3)
latent_dimensions = 100
#Step 4: Define a utility function to build the generator.
def build_generator():
model = Sequential()
#Building the input layer
model.add(Dense(128 * 8 * 8, activation="relu",
input_dim=latent_dimensions))
model.add(Reshape((8, 8, 128)))
model.add(UpSampling2D())
model.add(Conv2D(128, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.78))
model.add(Activation("relu"))
model.add(UpSampling2D())
model.add(Conv2D(64, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.78))
model.add(Activation("relu"))
model.add(Conv2D(3, kernel_size=3, padding="same"))
model.add(Activation("tanh"))
#Generating the output image
noise = Input(shape=(latent_dimensions,))
image = model(noise)
return Model(noise, image)
#Step 5: Define a utility function to build the discriminator.
def build_discriminator():
#Building the convolutional layers
#to classify whether an image is real or fake
model = Sequential()
model.add(Conv2D(32, kernel_size=3, strides=2,
input_shape=image_shape, padding="same"))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size=3, strides=2, padding="same"))
model.add(ZeroPadding2D(padding=((0,1),(0,1))))
model.add(BatchNormalization(momentum=0.82))
model.add(LeakyReLU(alpha=0.25))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization(momentum=0.82))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(256, kernel_size=3, strides=1, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.25))
model.add(Dropout(0.25))
#Building the output layer
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
image = Input(shape=image_shape)
validity = model(image)
return Model(image, validity)
#Step 6: Define a utility function to display the generated images.
def display_images():
# Generate a batch of random noise
noise = np.random.normal(0, 1, (16, latent_dimensions))
# Generate images from the noise
generated_images = generator.predict(noise)
# Rescale the images to 0-1 range
generated_images = 0.5 * generated_images + 0.5
# Plot the generated images
plt.figure(figsize=(6, 6))
for i in range(generated_images.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(generated_images[i])
plt.axis('off')
plt.tight_layout()
plt.show()
plt.close()
#Step 7: Build the GAN.
# Building and compiling the discriminator
discriminator = build_discriminator()
discriminator.compile(loss='binary_crossentropy',
optimizer=Adam(0.0002,0.5),
metrics=['accuracy'])
#Making the discriminator untrainable
#so that the generator can learn from fixed gradient
discriminator.trainable = False
# Building the generator
generator = build_generator()
#Defining the input for the generator
#and generating the images
z = Input(shape=(latent_dimensions,))
image = generator(z)
#Checking the validity of the generated image
valid = discriminator(image)
#Defining the combined model of the generator and the discriminator
combined_network = Model(z, valid)
combined_network.compile(loss='binary_crossentropy',
optimizer=Adam(0.0002,0.5))
#Step 8: Train the network.
num_epochs=15000
batch_size=32
display_interval=1000
losses=[]
#Normalizing the input
X = (X / 127.5) - 1.
#Defining the Adversarial ground truths
valid = np.ones((batch_size, 1))
#Adding some noise
valid += 0.05 * np.random.random(valid.shape)
fake = np.zeros((batch_size, 1))
fake += 0.05 * np.random.random(fake.shape)
for epoch in range(num_epochs):
#Training the Discriminator
#Sampling a random half of images
index = np.random.randint(0, X.shape[0], batch_size)
images = X[index]
#Sampling noise and generating a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dimensions))
generated_images = generator.predict(noise)
#Training the discriminator to detect more accurately
#whether a generated image is real or fake
discm_loss_real = discriminator.train_on_batch(images, valid)
discm_loss_fake = discriminator.train_on_batch(generated_images, fake)
discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake)
#Training the Generator
#Sampling noise and generating a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dimensions))
misleading_targets = np.ones((batch_size, 1))
#Training the generator to generate images
#that pass the authenticity test
genr_loss = combined_network.train_on_batch(noise, misleading_targets)
# Display generated images at the end of every 1000th epoch
#Tracking the progress
if epoch % display_interval == 0:
display_images()
noise = np.random.normal(0, 1, (16, latent_dimensions))
generated_images = generator.predict(noise)
generated_images = 0.5 * generated_images + 0.5
plt.figure(figsize=(6, 6))
for i in range(generated_images.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(generated_images[i])
plt.axis('off')
plt.tight_layout()
plt.savefig(f"epoch_{epoch+1}.png")
plt.close()
#Printing the progress and losses of the current epoch
print(f"Epoch {epoch} Discriminator Loss: {discm_loss[0]} Generator Loss:
{genr_loss}")

More Related Content

Similar to Need an detailed analysis of what this code-model is doing- Thanks #St.pdf

Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxLukeQVdGrantg
 
AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfssuserb4d806
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Ganesan Narayanasamy
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceLviv Startup Club
 
I have tried running this code below- and it is working- but the accur.pdf
I have tried running this code below- and it is working- but the accur.pdfI have tried running this code below- and it is working- but the accur.pdf
I have tried running this code below- and it is working- but the accur.pdfGordonF2XPatersonh
 
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdfI want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdfGordonF2XPatersonh
 
Introduction to deep learning using python
Introduction to deep learning using pythonIntroduction to deep learning using python
Introduction to deep learning using pythonLino Coria
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3San Kim
 
Assignment 6.1.pdf
Assignment 6.1.pdfAssignment 6.1.pdf
Assignment 6.1.pdfdash41
 
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...Publicis Sapient Engineering
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxTseChris
 
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfHello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfIan0J2Bondo
 
What is the UML Class diagram for accident detection using CNN- i have.pdf
What is the UML Class diagram for accident detection using CNN- i have.pdfWhat is the UML Class diagram for accident detection using CNN- i have.pdf
What is the UML Class diagram for accident detection using CNN- i have.pdfanilagarwal8880432
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 

Similar to Need an detailed analysis of what this code-model is doing- Thanks #St.pdf (20)

Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docx
 
AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdf
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
 
I have tried running this code below- and it is working- but the accur.pdf
I have tried running this code below- and it is working- but the accur.pdfI have tried running this code below- and it is working- but the accur.pdf
I have tried running this code below- and it is working- but the accur.pdf
 
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdfI want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
 
Scmad Chapter07
Scmad Chapter07Scmad Chapter07
Scmad Chapter07
 
Introduction to deep learning using python
Introduction to deep learning using pythonIntroduction to deep learning using python
Introduction to deep learning using python
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3
 
Assignment 6.1.pdf
Assignment 6.1.pdfAssignment 6.1.pdf
Assignment 6.1.pdf
 
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
 
Gans
GansGans
Gans
 
GANs
GANsGANs
GANs
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfHello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
 
What is the UML Class diagram for accident detection using CNN- i have.pdf
What is the UML Class diagram for accident detection using CNN- i have.pdfWhat is the UML Class diagram for accident detection using CNN- i have.pdf
What is the UML Class diagram for accident detection using CNN- i have.pdf
 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
Dive Into PyTorch
Dive Into PyTorchDive Into PyTorch
Dive Into PyTorch
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 

More from actexerode

Number of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfNumber of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfactexerode
 
Number of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfNumber of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfactexerode
 
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfNowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfactexerode
 
Now your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfNow your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfactexerode
 
Now that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfNow that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfactexerode
 
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfNote- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfactexerode
 
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfNow add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfactexerode
 
Note on vegetarians and type of vegetarians-Must be well explained.pdf
Note on vegetarians and type  of vegetarians-Must be well explained.pdfNote on vegetarians and type  of vegetarians-Must be well explained.pdf
Note on vegetarians and type of vegetarians-Must be well explained.pdfactexerode
 
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfNot yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfactexerode
 
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfNormal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfactexerode
 
Neman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfNeman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfactexerode
 
Night ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfNight ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfactexerode
 
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfNewton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfactexerode
 
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfNew DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfactexerode
 
New devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfNew devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfactexerode
 
Networking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfNetworking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfactexerode
 
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfNetwork standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfactexerode
 
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfnetflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfactexerode
 
Netflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfNetflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfactexerode
 
Negative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfNegative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfactexerode
 

More from actexerode (20)

Number of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfNumber of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdf
 
Number of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfNumber of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdf
 
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfNowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
 
Now your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfNow your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdf
 
Now that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfNow that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdf
 
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfNote- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
 
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfNow add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
 
Note on vegetarians and type of vegetarians-Must be well explained.pdf
Note on vegetarians and type  of vegetarians-Must be well explained.pdfNote on vegetarians and type  of vegetarians-Must be well explained.pdf
Note on vegetarians and type of vegetarians-Must be well explained.pdf
 
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfNot yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
 
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfNormal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
 
Neman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfNeman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdf
 
Night ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfNight ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdf
 
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfNewton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
 
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfNew DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
 
New devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfNew devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdf
 
Networking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfNetworking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdf
 
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfNetwork standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
 
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfnetflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
 
Netflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfNetflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdf
 
Negative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfNegative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdf
 

Recently uploaded

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 

Recently uploaded (20)

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 

Need an detailed analysis of what this code-model is doing- Thanks #St.pdf

  • 1. Need an detailed analysis of what this code/model is doing. Thanks #Step 1: Import the required Python libraries: import numpy as np import matplotlib.pyplot as plt import keras from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D from keras.models import Sequential, Model from keras.optimizers import Adam,SGD from keras.datasets import cifar10 #Step 2: Load the data. #Loading the CIFAR10 data (X, y), (_, _) = keras.datasets.cifar10.load_data() #Selecting a single class of images #The number was randomly chosen and any number #between 1 and 10 can be chosen X = X[y.flatten() == 8] #Step 3: Define parameters to be used in later processes. #Defining the Input shape image_shape = (32, 32, 3) latent_dimensions = 100
  • 2. #Step 4: Define a utility function to build the generator. def build_generator(): model = Sequential() #Building the input layer model.add(Dense(128 * 8 * 8, activation="relu", input_dim=latent_dimensions)) model.add(Reshape((8, 8, 128))) model.add(UpSampling2D()) model.add(Conv2D(128, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(UpSampling2D()) model.add(Conv2D(64, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(Conv2D(3, kernel_size=3, padding="same")) model.add(Activation("tanh")) #Generating the output image noise = Input(shape=(latent_dimensions,)) image = model(noise) return Model(noise, image) #Step 5: Define a utility function to build the discriminator. def build_discriminator():
  • 3. #Building the convolutional layers #to classify whether an image is real or fake model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding="same")) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) model.add(ZeroPadding2D(padding=((0,1),(0,1)))) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) #Building the output layer model.add(Flatten()) model.add(Dense(1, activation='sigmoid'))
  • 4. image = Input(shape=image_shape) validity = model(image) return Model(image, validity) #Step 6: Define a utility function to display the generated images. def display_images(): # Generate a batch of random noise noise = np.random.normal(0, 1, (16, latent_dimensions)) # Generate images from the noise generated_images = generator.predict(noise) # Rescale the images to 0-1 range generated_images = 0.5 * generated_images + 0.5 # Plot the generated images plt.figure(figsize=(6, 6)) for i in range(generated_images.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(generated_images[i]) plt.axis('off') plt.tight_layout() plt.show() plt.close() #Step 7: Build the GAN. # Building and compiling the discriminator discriminator = build_discriminator()
  • 5. discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5), metrics=['accuracy']) #Making the discriminator untrainable #so that the generator can learn from fixed gradient discriminator.trainable = False # Building the generator generator = build_generator() #Defining the input for the generator #and generating the images z = Input(shape=(latent_dimensions,)) image = generator(z) #Checking the validity of the generated image valid = discriminator(image) #Defining the combined model of the generator and the discriminator combined_network = Model(z, valid) combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5)) #Step 8: Train the network. num_epochs=15000 batch_size=32 display_interval=1000
  • 6. losses=[] #Normalizing the input X = (X / 127.5) - 1. #Defining the Adversarial ground truths valid = np.ones((batch_size, 1)) #Adding some noise valid += 0.05 * np.random.random(valid.shape) fake = np.zeros((batch_size, 1)) fake += 0.05 * np.random.random(fake.shape) for epoch in range(num_epochs): #Training the Discriminator #Sampling a random half of images index = np.random.randint(0, X.shape[0], batch_size) images = X[index] #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) generated_images = generator.predict(noise) #Training the discriminator to detect more accurately #whether a generated image is real or fake discm_loss_real = discriminator.train_on_batch(images, valid) discm_loss_fake = discriminator.train_on_batch(generated_images, fake) discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake)
  • 7. #Training the Generator #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) misleading_targets = np.ones((batch_size, 1)) #Training the generator to generate images #that pass the authenticity test genr_loss = combined_network.train_on_batch(noise, misleading_targets) # Display generated images at the end of every 1000th epoch #Tracking the progress if epoch % display_interval == 0: display_images() noise = np.random.normal(0, 1, (16, latent_dimensions)) generated_images = generator.predict(noise) generated_images = 0.5 * generated_images + 0.5 plt.figure(figsize=(6, 6)) for i in range(generated_images.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(generated_images[i]) plt.axis('off') plt.tight_layout() plt.savefig(f"epoch_{epoch+1}.png") plt.close() #Printing the progress and losses of the current epoch
  • 8. print(f"Epoch {epoch} Discriminator Loss: {discm_loss[0]} Generator Loss: {genr_loss}") #Step 1: Import the required Python libraries: import numpy as np import matplotlib.pyplot as plt import keras from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D from keras.models import Sequential, Model from keras.optimizers import Adam,SGD from keras.datasets import cifar10 #Step 2: Load the data. #Loading the CIFAR10 data (X, y), (_, _) = keras.datasets.cifar10.load_data() #Selecting a single class of images #The number was randomly chosen and any number #between 1 and 10 can be chosen X = X[y.flatten() == 8] #Step 3: Define parameters to be used in later processes. #Defining the Input shape image_shape = (32, 32, 3) latent_dimensions = 100
  • 9. #Step 4: Define a utility function to build the generator. def build_generator(): model = Sequential() #Building the input layer model.add(Dense(128 * 8 * 8, activation="relu", input_dim=latent_dimensions)) model.add(Reshape((8, 8, 128))) model.add(UpSampling2D()) model.add(Conv2D(128, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(UpSampling2D()) model.add(Conv2D(64, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(Conv2D(3, kernel_size=3, padding="same")) model.add(Activation("tanh")) #Generating the output image noise = Input(shape=(latent_dimensions,)) image = model(noise) return Model(noise, image) #Step 5: Define a utility function to build the discriminator. def build_discriminator():
  • 10. #Building the convolutional layers #to classify whether an image is real or fake model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding="same")) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) model.add(ZeroPadding2D(padding=((0,1),(0,1)))) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) #Building the output layer model.add(Flatten()) model.add(Dense(1, activation='sigmoid'))
  • 11. image = Input(shape=image_shape) validity = model(image) return Model(image, validity) #Step 6: Define a utility function to display the generated images. def display_images(): # Generate a batch of random noise noise = np.random.normal(0, 1, (16, latent_dimensions)) # Generate images from the noise generated_images = generator.predict(noise) # Rescale the images to 0-1 range generated_images = 0.5 * generated_images + 0.5 # Plot the generated images plt.figure(figsize=(6, 6)) for i in range(generated_images.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(generated_images[i]) plt.axis('off') plt.tight_layout() plt.show() plt.close() #Step 7: Build the GAN. # Building and compiling the discriminator discriminator = build_discriminator()
  • 12. discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5), metrics=['accuracy']) #Making the discriminator untrainable #so that the generator can learn from fixed gradient discriminator.trainable = False # Building the generator generator = build_generator() #Defining the input for the generator #and generating the images z = Input(shape=(latent_dimensions,)) image = generator(z) #Checking the validity of the generated image valid = discriminator(image) #Defining the combined model of the generator and the discriminator combined_network = Model(z, valid) combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5)) #Step 8: Train the network. num_epochs=15000 batch_size=32 display_interval=1000
  • 13. losses=[] #Normalizing the input X = (X / 127.5) - 1. #Defining the Adversarial ground truths valid = np.ones((batch_size, 1)) #Adding some noise valid += 0.05 * np.random.random(valid.shape) fake = np.zeros((batch_size, 1)) fake += 0.05 * np.random.random(fake.shape) for epoch in range(num_epochs): #Training the Discriminator #Sampling a random half of images index = np.random.randint(0, X.shape[0], batch_size) images = X[index] #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) generated_images = generator.predict(noise) #Training the discriminator to detect more accurately #whether a generated image is real or fake discm_loss_real = discriminator.train_on_batch(images, valid) discm_loss_fake = discriminator.train_on_batch(generated_images, fake) discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake)
  • 14. #Training the Generator #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) misleading_targets = np.ones((batch_size, 1)) #Training the generator to generate images #that pass the authenticity test genr_loss = combined_network.train_on_batch(noise, misleading_targets) # Display generated images at the end of every 1000th epoch #Tracking the progress if epoch % display_interval == 0: display_images() noise = np.random.normal(0, 1, (16, latent_dimensions)) generated_images = generator.predict(noise) generated_images = 0.5 * generated_images + 0.5 plt.figure(figsize=(6, 6)) for i in range(generated_images.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(generated_images[i]) plt.axis('off') plt.tight_layout() plt.savefig(f"epoch_{epoch+1}.png") plt.close() #Printing the progress and losses of the current epoch
  • 15. print(f"Epoch {epoch} Discriminator Loss: {discm_loss[0]} Generator Loss: {genr_loss}")