SlideShare a Scribd company logo
1 of 13
Download to read offline
Can someone please explain what the code below is doing and comment on its network
performance? Please and thank you.
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
#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]
#Defining the Input shape
image_shape = (32, 32, 3)
latent_dimensions = 100
#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)
#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():
r, c = 4,4
noise = np.random.normal(0, 1, (r * c,latent_dimensions))
generated_images = generator.predict(noise)
#Scaling the generated images
generated_images = 0.5 * generated_images + 0.5
fig, axs = plt.subplots(r, c)
count = 0
for i in range(r):
for j in range(c):
axs[i,j].imshow(generated_images[count, :,:,])
axs[i,j].axis('off')
count += 1
plt.show()
plt.close()
.
# 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=2500
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
#Training the generator to generate images
#that pass the authenticity test
genr_loss = combined_network.train_on_batch(noise, valid)
#Tracking the progress
if epoch % display_interval == 0:
display_images()
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
#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]
#Defining the Input shape
image_shape = (32, 32, 3)
latent_dimensions = 100
#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)
#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():
r, c = 4,4
noise = np.random.normal(0, 1, (r * c,latent_dimensions))
generated_images = generator.predict(noise)
#Scaling the generated images
generated_images = 0.5 * generated_images + 0.5
fig, axs = plt.subplots(r, c)
count = 0
for i in range(r):
for j in range(c):
axs[i,j].imshow(generated_images[count, :,:,])
axs[i,j].axis('off')
count += 1
plt.show()
plt.close()
.
# 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=2500
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
#Training the generator to generate images
#that pass the authenticity test
genr_loss = combined_network.train_on_batch(noise, valid)
#Tracking the progress
if epoch % display_interval == 0:
display_images()

More Related Content

Similar to Can someone please explain what the code below is doing and comment on.pdf

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
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnnDebarko De
 
29-kashyap-mask-detaction.pptx
29-kashyap-mask-detaction.pptx29-kashyap-mask-detaction.pptx
29-kashyap-mask-detaction.pptxKASHYAPPATHAK7
 
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.pdfMattU5mLambertq
 
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
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3San Kim
 
I have to understand this code and i have to explain the each line of.pdf
I have to understand this code and i have to explain the each line of.pdfI have to understand this code and i have to explain the each line of.pdf
I have to understand this code and i have to explain the each line of.pdfshreeaadithyaacellso
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Thomas Fan
 
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
 
The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84Mahmoud Samir Fayed
 
Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Fwdays
 
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
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_TitanicAliciaWei1
 
The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84Mahmoud Samir Fayed
 

Similar to Can someone please explain what the code below is doing and comment on.pdf (20)

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
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnn
 
29-kashyap-mask-detaction.pptx
29-kashyap-mask-detaction.pptx29-kashyap-mask-detaction.pptx
29-kashyap-mask-detaction.pptx
 
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
 
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
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3
 
I have to understand this code and i have to explain the each line of.pdf
I have to understand this code and i have to explain the each line of.pdfI have to understand this code and i have to explain the each line of.pdf
I have to understand this code and i have to explain the each line of.pdf
 
Scmad Chapter07
Scmad Chapter07Scmad Chapter07
Scmad Chapter07
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
 
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
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84
 
Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"
 
alexnet.pdf
alexnet.pdfalexnet.pdf
alexnet.pdf
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_Titanic
 
The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84
 

More from kuldeepkumarapgsi

Can someone help me- I feel like I'm doing my calculations wrong when.pdf
Can someone help me- I feel like I'm doing my calculations wrong when.pdfCan someone help me- I feel like I'm doing my calculations wrong when.pdf
Can someone help me- I feel like I'm doing my calculations wrong when.pdfkuldeepkumarapgsi
 
Can someone explain to me what this code does in the first section- Th.pdf
Can someone explain to me what this code does in the first section- Th.pdfCan someone explain to me what this code does in the first section- Th.pdf
Can someone explain to me what this code does in the first section- Th.pdfkuldeepkumarapgsi
 
Can i please get help with C (a) What is the probability that in a ran.pdf
Can i please get help with C (a) What is the probability that in a ran.pdfCan i please get help with C (a) What is the probability that in a ran.pdf
Can i please get help with C (a) What is the probability that in a ran.pdfkuldeepkumarapgsi
 
Calculate the expected return for two possible outcomes for the econom.pdf
Calculate the expected return for two possible outcomes for the econom.pdfCalculate the expected return for two possible outcomes for the econom.pdf
Calculate the expected return for two possible outcomes for the econom.pdfkuldeepkumarapgsi
 
Calculate the average rate of increase in CO2 concentration between 17.pdf
Calculate the average rate of increase in CO2 concentration between 17.pdfCalculate the average rate of increase in CO2 concentration between 17.pdf
Calculate the average rate of increase in CO2 concentration between 17.pdfkuldeepkumarapgsi
 
Calculate the average (mean) of the data shown- to two decimal places.pdf
Calculate the average (mean) of the data shown- to two decimal places.pdfCalculate the average (mean) of the data shown- to two decimal places.pdf
Calculate the average (mean) of the data shown- to two decimal places.pdfkuldeepkumarapgsi
 
Calculate P(z0-3) Round answer to 4 decimal places-.pdf
Calculate P(z0-3) Round answer to 4 decimal places-.pdfCalculate P(z0-3) Round answer to 4 decimal places-.pdf
Calculate P(z0-3) Round answer to 4 decimal places-.pdfkuldeepkumarapgsi
 
calculate debt to equity- debt to total capital employed- interest cov.pdf
calculate debt to equity- debt to total capital employed- interest cov.pdfcalculate debt to equity- debt to total capital employed- interest cov.pdf
calculate debt to equity- debt to total capital employed- interest cov.pdfkuldeepkumarapgsi
 
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdf
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdfC-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdf
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdfkuldeepkumarapgsi
 
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdf
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdfCalcilale itis A- 15- D- 13- C- 14- D- 17-.pdf
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdfkuldeepkumarapgsi
 
Cacti live in the hot desert and can easily lose water during the day-.pdf
Cacti live in the hot desert and can easily lose water during the day-.pdfCacti live in the hot desert and can easily lose water during the day-.pdf
Cacti live in the hot desert and can easily lose water during the day-.pdfkuldeepkumarapgsi
 
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdf
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdfC-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdf
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdfkuldeepkumarapgsi
 
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdf
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdfc- The triceps is the prime mover and the anconeus a weak auxistant in.pdf
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdfkuldeepkumarapgsi
 
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdf
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdfc- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdf
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdfkuldeepkumarapgsi
 
C- Amyotrophic Lateral Sclerosis (ALS)- 1- How would you explain ALS.pdf
C- Amyotrophic Lateral Sclerosis (ALS)-   1- How would you explain ALS.pdfC- Amyotrophic Lateral Sclerosis (ALS)-   1- How would you explain ALS.pdf
C- Amyotrophic Lateral Sclerosis (ALS)- 1- How would you explain ALS.pdfkuldeepkumarapgsi
 
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdf
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdfC++ in MS Visual Studio- continues to receive error code E0276 (identi.pdf
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdfkuldeepkumarapgsi
 
Business Study Guide 8-What is the relationship between the goods an.pdf
Business Study Guide   8-What is the relationship between the goods an.pdfBusiness Study Guide   8-What is the relationship between the goods an.pdf
Business Study Guide 8-What is the relationship between the goods an.pdfkuldeepkumarapgsi
 
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdf
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdfc++ #include -iostream- using namespace std- void InsertionSort(int nu.pdf
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdfkuldeepkumarapgsi
 
C# There are two int variables- a-8 and b-2- What will be the values o.pdf
C# There are two int variables- a-8 and b-2- What will be the values o.pdfC# There are two int variables- a-8 and b-2- What will be the values o.pdf
C# There are two int variables- a-8 and b-2- What will be the values o.pdfkuldeepkumarapgsi
 
C# Visual studio 2017 Find and mention in detail all possible error(s).pdf
C# Visual studio 2017 Find and mention in detail all possible error(s).pdfC# Visual studio 2017 Find and mention in detail all possible error(s).pdf
C# Visual studio 2017 Find and mention in detail all possible error(s).pdfkuldeepkumarapgsi
 

More from kuldeepkumarapgsi (20)

Can someone help me- I feel like I'm doing my calculations wrong when.pdf
Can someone help me- I feel like I'm doing my calculations wrong when.pdfCan someone help me- I feel like I'm doing my calculations wrong when.pdf
Can someone help me- I feel like I'm doing my calculations wrong when.pdf
 
Can someone explain to me what this code does in the first section- Th.pdf
Can someone explain to me what this code does in the first section- Th.pdfCan someone explain to me what this code does in the first section- Th.pdf
Can someone explain to me what this code does in the first section- Th.pdf
 
Can i please get help with C (a) What is the probability that in a ran.pdf
Can i please get help with C (a) What is the probability that in a ran.pdfCan i please get help with C (a) What is the probability that in a ran.pdf
Can i please get help with C (a) What is the probability that in a ran.pdf
 
Calculate the expected return for two possible outcomes for the econom.pdf
Calculate the expected return for two possible outcomes for the econom.pdfCalculate the expected return for two possible outcomes for the econom.pdf
Calculate the expected return for two possible outcomes for the econom.pdf
 
Calculate the average rate of increase in CO2 concentration between 17.pdf
Calculate the average rate of increase in CO2 concentration between 17.pdfCalculate the average rate of increase in CO2 concentration between 17.pdf
Calculate the average rate of increase in CO2 concentration between 17.pdf
 
Calculate the average (mean) of the data shown- to two decimal places.pdf
Calculate the average (mean) of the data shown- to two decimal places.pdfCalculate the average (mean) of the data shown- to two decimal places.pdf
Calculate the average (mean) of the data shown- to two decimal places.pdf
 
Calculate P(z0-3) Round answer to 4 decimal places-.pdf
Calculate P(z0-3) Round answer to 4 decimal places-.pdfCalculate P(z0-3) Round answer to 4 decimal places-.pdf
Calculate P(z0-3) Round answer to 4 decimal places-.pdf
 
calculate debt to equity- debt to total capital employed- interest cov.pdf
calculate debt to equity- debt to total capital employed- interest cov.pdfcalculate debt to equity- debt to total capital employed- interest cov.pdf
calculate debt to equity- debt to total capital employed- interest cov.pdf
 
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdf
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdfC-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdf
C-mon miztrie (nor month)The figure above shows a consumer is indiffer.pdf
 
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdf
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdfCalcilale itis A- 15- D- 13- C- 14- D- 17-.pdf
Calcilale itis A- 15- D- 13- C- 14- D- 17-.pdf
 
Cacti live in the hot desert and can easily lose water during the day-.pdf
Cacti live in the hot desert and can easily lose water during the day-.pdfCacti live in the hot desert and can easily lose water during the day-.pdf
Cacti live in the hot desert and can easily lose water during the day-.pdf
 
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdf
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdfC-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdf
C-D as your answers) A- Facilitated transport B- Simple diffusion C- A.pdf
 
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdf
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdfc- The triceps is the prime mover and the anconeus a weak auxistant in.pdf
c- The triceps is the prime mover and the anconeus a weak auxistant in.pdf
 
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdf
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdfc- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdf
c- Motor vs- Sensory Efferent neurons (or neurons) carry signals away.pdf
 
C- Amyotrophic Lateral Sclerosis (ALS)- 1- How would you explain ALS.pdf
C- Amyotrophic Lateral Sclerosis (ALS)-   1- How would you explain ALS.pdfC- Amyotrophic Lateral Sclerosis (ALS)-   1- How would you explain ALS.pdf
C- Amyotrophic Lateral Sclerosis (ALS)- 1- How would you explain ALS.pdf
 
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdf
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdfC++ in MS Visual Studio- continues to receive error code E0276 (identi.pdf
C++ in MS Visual Studio- continues to receive error code E0276 (identi.pdf
 
Business Study Guide 8-What is the relationship between the goods an.pdf
Business Study Guide   8-What is the relationship between the goods an.pdfBusiness Study Guide   8-What is the relationship between the goods an.pdf
Business Study Guide 8-What is the relationship between the goods an.pdf
 
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdf
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdfc++ #include -iostream- using namespace std- void InsertionSort(int nu.pdf
c++ #include -iostream- using namespace std- void InsertionSort(int nu.pdf
 
C# There are two int variables- a-8 and b-2- What will be the values o.pdf
C# There are two int variables- a-8 and b-2- What will be the values o.pdfC# There are two int variables- a-8 and b-2- What will be the values o.pdf
C# There are two int variables- a-8 and b-2- What will be the values o.pdf
 
C# Visual studio 2017 Find and mention in detail all possible error(s).pdf
C# Visual studio 2017 Find and mention in detail all possible error(s).pdfC# Visual studio 2017 Find and mention in detail all possible error(s).pdf
C# Visual studio 2017 Find and mention in detail all possible error(s).pdf
 

Recently uploaded

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
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
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
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
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Can someone please explain what the code below is doing and comment on.pdf

  • 1. Can someone please explain what the code below is doing and comment on its network performance? Please and thank you. 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 #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] #Defining the Input shape image_shape = (32, 32, 3) latent_dimensions = 100 #Define a utility function to build the generator. def build_generator(): model = Sequential()
  • 2. #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) #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()
  • 3. 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)
  • 4. #Step 6: Define a utility function to display the generated images. def display_images(): r, c = 4,4 noise = np.random.normal(0, 1, (r * c,latent_dimensions)) generated_images = generator.predict(noise) #Scaling the generated images generated_images = 0.5 * generated_images + 0.5 fig, axs = plt.subplots(r, c) count = 0 for i in range(r): for j in range(c): axs[i,j].imshow(generated_images[count, :,:,]) axs[i,j].axis('off') count += 1 plt.show() plt.close() . # 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
  • 5. #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=2500 losses=[] #Normalizing the input X = (X / 127.5) - 1. #Defining the Adversarial ground truths valid = np.ones((batch_size, 1))
  • 6. #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 #Training the generator to generate images #that pass the authenticity test genr_loss = combined_network.train_on_batch(noise, valid) #Tracking the progress if epoch % display_interval == 0:
  • 7. display_images() 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 #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] #Defining the Input shape image_shape = (32, 32, 3) latent_dimensions = 100 #Define a utility function to build the generator. def build_generator(): model = Sequential()
  • 8. #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) #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()
  • 9. 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)
  • 10. #Step 6: Define a utility function to display the generated images. def display_images(): r, c = 4,4 noise = np.random.normal(0, 1, (r * c,latent_dimensions)) generated_images = generator.predict(noise) #Scaling the generated images generated_images = 0.5 * generated_images + 0.5 fig, axs = plt.subplots(r, c) count = 0 for i in range(r): for j in range(c): axs[i,j].imshow(generated_images[count, :,:,]) axs[i,j].axis('off') count += 1 plt.show() plt.close() . # 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
  • 11. #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=2500 losses=[] #Normalizing the input X = (X / 127.5) - 1. #Defining the Adversarial ground truths valid = np.ones((batch_size, 1))
  • 12. #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 #Training the generator to generate images #that pass the authenticity test genr_loss = combined_network.train_on_batch(noise, valid) #Tracking the progress if epoch % display_interval == 0: