import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *

(x,_),_=tf.keras.datasets.mnist.load_data()
x=x.astype('float32')/255;x=x.reshape(-1,28,28,1)

G=Sequential([Dense(256,input_dim=100),LeakyReLU(.2),
Dense(512),LeakyReLU(.2),Dense(1024),LeakyReLU(.2),
Dense(784,activation='tanh'),Reshape((28,28,1))])

D=Sequential([Flatten(input_shape=(28,28,1)),
Dense(512),LeakyReLU(.2),Dense(256),LeakyReLU(.2),
Dense(1,activation='sigmoid')])

D.compile('adam','binary_crossentropy')
D.trainable=False
gan=Sequential([G,D]);gan.compile('adam','binary_crossentropy')

for e in range(10):
 z=np.random.randn(32,100);f=G.predict(z,verbose=0)
 r=x[np.random.randint(len(x),size=32)]
 D.train_on_batch(r,np.ones((32,1)))
 D.train_on_batch(f,np.zeros((32,1)))
 gan.train_on_batch(z,np.ones((32,1)))

z=np.random.randn(25,100);g=G.predict(z,verbose=0)
for i in range(25):
 plt.subplot(5,5,i+1);plt.imshow(g[i,:,:,0],cmap='gray');plt.axis('off')
plt.show()