Start the TensorFlow session and generate handwritten digits:
with tf.Session() as session:
Initialize all variables:
session.run(init)
To execute this for each epoch:
for epoch in range(num_epochs):
Select the number of batches:
num_batches = data.train.num_examples // batch_size
To execute this for each batch:
for i in range(num_batches):
Get the batch of data according to the batch size:
batch = data.train.next_batch(batch_size)
Reshape the data:
batch_images = batch[0].reshape((batch_size,784))
batch_images = batch_images * 2 - 1
Sample the batch noise:
batch_noise = np.random.uniform(-1,1,size=(batch_size,100))
Define the feed dictionaries with input x as batch_images and noise z as batch_noise:
feed_dict = {x: batch_images, z : batch_noise}
Train the discriminator and generator:
_ = session.run(D_optimizer,feed_dict = feed_dict)
_ = session.run(G_optimizer,feed_dict = feed_dict)
Compute loss of discriminator and generator:
discriminator_loss = D_loss.eval(feed_dict)
generator_loss = G_loss.eval(feed_dict)
Feed the noise to a generator on every 100th epoch and generate an image:
if epoch%100==0:
print("Epoch: {}, iteration: {}, Discriminator Loss:{}, Generator Loss: {}".format(epoch,i,discriminator_loss,generator_loss))
_fake_x = fake_x.eval(feed_dict)
plt.imshow(_fake_x[0].reshape(28,28))
plt.show()
During training, we notice how loss decreases and how GANs learn to generate images as shown follows: