woodsja

pong_VAE.py

Jan 14th, 2019
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """Pong_VAE
  3.  
  4. Automatically generated by Colaboratory.
  5.  
  6. Original file is located at
  7.    https://colab.research.google.com/drive/1Q9Uhc5MgM8hkT_YpEQQw5OmpTWC2Z3Yd
  8. """
  9.  
  10. """What does a VAE of the observation space for Pong-v0 look like?
  11. Uses code from the autoencoder tut from keras
  12. """
  13.  
  14. from keras.datasets import mnist
  15.  
  16. import gym
  17.  
  18. from keras.layers import Lambda, Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Reshape
  19. from keras.models import Model
  20. from keras.losses import mse, binary_crossentropy
  21. from keras.utils import plot_model
  22. from keras import backend as K
  23. from keras.callbacks import TensorBoard
  24.  
  25. from IPython.display import SVG
  26. from keras.utils.vis_utils import model_to_dot
  27.  
  28. import numpy as np
  29. import matplotlib.pyplot as plt
  30. import argparse
  31. import random
  32. import os
  33. # %matplotlib inline
  34.  
  35. def get_data2D(data_dim=(105,80), environment='Pong-v0', number_of_examples=1000, render=False):
  36.     """
  37.    Runs a bunch of random actions in the chosen Atari environment and screen captures the downscaled/grayscaled images
  38.    :param data_dim: product of dims of the data that you wanna store e.g. 210*160=33600
  39.    :param environment: Defaults to Pong-v0 environment, adaptable to any Atari game in Gym
  40.    :param number_of_examples: 1000 examples is pretty quick to generate
  41.    :param render: Do you want to render this?
  42.    :return: the data that we just made
  43.    """
  44.     env = gym.make(environment)
  45.     observation = env.reset()
  46.     done = False
  47.     episode_limit = 2000
  48.  
  49.     data = np.zeros((number_of_examples, 8400), dtype=float)
  50.     counter = 0
  51.     while counter < number_of_examples - 1:
  52.         for t in range(episode_limit):
  53.             if render:
  54.                 env.render()
  55.  
  56.             action = env.action_space.sample()
  57.             observation, reward, done, info = env.step(action)
  58.                        
  59.             buffer = observation.astype('float32') / 255
  60.             buffer = buffer[::2, ::2]
  61.             buffer = rgb2_gray(buffer)
  62.             buffer = np.reshape(buffer, [-1, 8400])
  63.            
  64.            
  65.             # number_of_examples is 1 indexed but counter is zero indexed...
  66.             # a lot of the sequential observations are the same pixel values
  67.             # checks to make sure it's new info                    
  68.             if counter < (number_of_examples - 1):
  69.                 if np.sum(buffer - data[counter - 1]) != 0.0:
  70.                     data[counter] = buffer
  71.                     counter += 1
  72.            
  73.             if done:
  74.                 print("Episode finished after {} timesteps".format(t + 1))
  75.                 env.reset()
  76.         print("Counter is {}".format(counter))
  77.     return data
  78.  
  79. def rgb2_gray(rgb):
  80.  
  81.     r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
  82.     gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
  83.     return gray
  84.  
  85. x_train = get_data2D(number_of_examples=10000)
  86. x_test = get_data2D(number_of_examples=1000)
  87.  
  88. plt.figure(figsize=(1,1))
  89. n = 4
  90.  
  91. f, axarr = plt.subplots(1,n)
  92. for i in range(n):
  93.   axarr[i].imshow(x_train[random.randint(0,len(x_train))].reshape(105,80))
  94.   axarr[i].axis('off')
  95. plt.show()
  96.  
  97. def sampling(args):
  98.     """reparameterization trick to sample from an isotropic unit gaussian
  99.  
  100.    :param args: (tensor) mean and log of variance Q(z|X)
  101.    :return: z (tensor) sampled latent vector
  102.    """
  103.  
  104.     z_mean, z_log_var = args
  105.     batch = K.shape(z_mean)[0]
  106.     dim = K.int_shape(z_mean)[1]
  107.     epsilon = K.random_normal(shape=(batch,dim))
  108.    
  109.     return z_mean + K.exp(0.5 * z_log_var) * epsilon
  110.  
  111. # network parameters
  112. original_dim = 8400
  113. input_shape = x_train[0].shape
  114. intermediate_dim = 512
  115. batch_size = 1024
  116. latent_dim = 10
  117. epochs = 50
  118.  
  119. # build encoder model
  120. inputs = Input(shape=input_shape, name='encoder_input')
  121. x= Dense(intermediate_dim, activation='relu', name='intermediate_encoder1')(inputs)
  122. #x= Dense(intermediate_dim, activation='relu', name='intermediate_encoder2')(x)
  123. z_mean = Dense(latent_dim, name='z_mean')(x)
  124. z_log_var = Dense(latent_dim, name='z_log_var')(x)
  125.  
  126. z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
  127.  
  128. encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')
  129. encoder.summary()
  130.  
  131. # build decoder model
  132. latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
  133. x = Dense(intermediate_dim, activation='relu', name='intermediate_decoder1')(latent_inputs)
  134. #x = Dense(intermediate_dim, activation='relu', name='intermediate_decoder2')(x)
  135. outputs = Dense(original_dim, activation='sigmoid', name='outputs')(x)
  136.  
  137. # instantiate decoder model
  138. decoder = Model(latent_inputs, outputs, name='decoder')
  139. decoder.summary()
  140.  
  141. # instantiate VAE model
  142. outputs = decoder(encoder(inputs)[2])
  143. vae = Model(inputs, outputs, name='VAE_MLP')
  144.  
  145. beta = 1.
  146.  
  147. reconstruction_loss = binary_crossentropy(inputs, outputs)
  148. reconstruction_loss *= original_dim
  149. kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
  150. kl_loss = K.sum(kl_loss, axis=-1)
  151. kl_loss *= -0.5
  152. vae_loss = K.mean(reconstruction_loss + beta * kl_loss)
  153. vae.add_loss(vae_loss)
  154. vae.compile(optimizer='adam')
  155. vae.summary()
  156.  
  157. vae.fit(x_train, epochs=epochs, batch_size=batch_size, shuffle=True, validation_data=(x_test, None))
  158. vae.save_weights('vae_mlp_pong.h5')
  159.  
  160. z_mean, z_log_sigma, z = encoder.predict(x_test, batch_size=batch_size)
  161. decoded_img = decoder.predict(z_mean)
  162.  
  163. plt.figure(figsize=(5,4))
  164. n = 4
  165.  
  166. f, axarr = plt.subplots(2,n)
  167. for i in range(n):
  168.   index = random.randint(0,len(x_test))
  169.   axarr[0,i].imshow(x_train[index].reshape(105,80))
  170.   axarr[0,i].axis('off')
  171.   axarr[1,i].imshow(decoded_img[index].reshape(105,80))
  172.   axarr[1,i].axis('off')
  173. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment