woodsja

How do I add Tensorboard monitoring?

Nov 26th, 2018
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.88 KB | None | 0 0
  1. import gym
  2. import tensorflow as tf
  3. from tensorflow.python.framework import ops
  4. import numpy as np
  5.  
  6. env = gym.make('CartPole-v1')
  7.  
  8. env.seed(1)
  9.  
  10. print("env.action_space", env.action_space)
  11. print("env.observation_space", env.observation_space)
  12. print("env.observation_space.high", env.observation_space.high)
  13. print("env.observation_space.low", env.observation_space.low)
  14.  
  15. RENDER_ENV = True
  16. EPISODES = 500
  17. rewards = []
  18. RENDER_REWARD_MIN = -1000
  19.  
  20. class PolicyGradient:
  21.   def __init__(self, n_x, n_y, learning_rate=0.01, reward_decay=0.95, load_path=None, save_path=None):
  22.     self.n_x = n_x
  23.     self.n_y = n_y
  24.     self.lr = learning_rate
  25.     self.gamma = reward_decay
  26.  
  27.     self.save_path = None
  28.     if save_path is not None:
  29.       self.save_path = save_path
  30.  
  31.     self.episode_observations = []
  32.     self.episode_actions = []
  33.     self.episode_rewards = []
  34.  
  35.     self.build_network()
  36.  
  37.     self.cost_history = []
  38.     self.sess = tf.Session()
  39.  
  40.     # $ tensorboard --logdir=logs
  41.     # http://0.0.0.0:6006/
  42.     tf.summary.FileWriter("logs/", self.sess.graph)
  43.  
  44.     self.sess.run(tf.global_variables_initializer())
  45.  
  46.     # saver op to save/restore all variables
  47.     self.saver = tf.train.Saver()
  48.  
  49.     # restore model
  50.     if load_path is not None:
  51.       self.load_path = load_path
  52.       self.saver.restore(self.sess, self.load_path)
  53.  
  54.   # trying to get tensorboard summaries working...
  55.  
  56.   def variable_summaries(self, var):
  57.     with tf.name_scope('summaries'):
  58.       mean = tf.reduce_mean(var)
  59.       tf.summary.scalar('mean', mean)
  60.       with tf.name_scope('stddev'):
  61.         stdev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
  62.       tf.summary.scalar('stddev', stddev)
  63.       tf.summary.scalar('max', tf.reduce_max(var))
  64.       tf.summary.scalar('min', tf.reduce_min(var))
  65.       tf.summary.histogram('histogram', var)
  66.  
  67.  
  68.   def build_network(self):
  69.     # create placeholders
  70.     with tf.name_scope('inputs'):
  71.       self.X = tf.placeholder(tf.float32, shape=(self.n_x, None), name="X")
  72.       self.Y = tf.placeholder(tf.float32, shape=(self.n_y, None), name="Y")
  73.       self.discounted_episode_rewards_norm = tf.placeholder(tf.float32, [None, ], name="actions_value")
  74.  
  75.     units_layer_1 = 10
  76.     units_layer_2 = 10
  77.     units_output_layer = self.n_y
  78.     with tf.name_scope('parameters'):
  79.       W1 = tf.get_variable("W1", [units_layer_1, self.n_x], initializer=tf.contrib.layers.xavier_initializer(seed=1))
  80.       b1 = tf.get_variable("b1", [units_layer_1, 1], initializer=tf.contrib.layers.xavier_initializer(seed=1))
  81.       W2 = tf.get_variable("W2", [units_layer_2, units_layer_1],
  82.                            initializer=tf.contrib.layers.xavier_initializer(seed=1))
  83.       b2 = tf.get_variable("b2", [units_layer_2, 1], initializer=tf.contrib.layers.xavier_initializer(seed=1))
  84.       W3 = tf.get_variable("W3", [self.n_y, units_layer_2], initializer=tf.contrib.layers.xavier_initializer(seed=1))
  85.       b3 = tf.get_variable("b3", [self.n_y, 1], initializer=tf.contrib.layers.xavier_initializer(seed=1))
  86.  
  87.     # forward prop
  88.     with tf.name_scope('layer_1'):
  89.       Z1 = tf.add(tf.matmul(W1, self.X), b1)
  90.       A1 = tf.nn.relu(Z1)
  91.     with tf.name_scope('layer_2'):
  92.       Z2 = tf.add(tf.matmul(W2, A1), b2)
  93.       A2 = tf.nn.relu(Z2)
  94.     with tf.name_scope('layer_3'):
  95.       Z3 = tf.add(tf.matmul(W3, A2), b3)
  96.       A3 = tf.nn.softmax(Z3)
  97.  
  98.     # softmax outputs need to be transposed
  99.     logits = tf.transpose(Z3)
  100.     labels = tf.transpose(self.Y)
  101.     self.outputs_softmax = tf.nn.softmax(logits, name='A3')
  102.  
  103.     with tf.name_scope('loss'):
  104.       neg_log_prob = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=labels)
  105.       loss = tf.reduce_mean(neg_log_prob * self.discounted_episode_rewards_norm)
  106.  
  107.     with tf.name_scope('train'):
  108.       self.train_op = tf.train.AdamOptimizer(self.lr).minimize(loss)
  109.  
  110.   def plot_cost(self):
  111.     import matplotlib
  112.     matplotlib.use("MacOSX")
  113.     import matplotlib.pyplot as plt
  114.     plt.plot(np.arange(len(self.cost_history)), self.cost_history)
  115.     plt.ylabel('Cost')
  116.     plt.xlabel('Training Steps')
  117.     plt.show()
  118.  
  119.   def discount_and_norm_rewards(self):
  120.     discounted_episode_rewards = np.zeros_like(self.episode_rewards)
  121.     cumulative = 0
  122.     for t in reversed(range(len(self.episode_rewards))):
  123.       cumulative = cumulative * self.gamma + self.episode_rewards[t]
  124.       discounted_episode_rewards[t] = cumulative
  125.  
  126.     discounted_episode_rewards -= np.mean(discounted_episode_rewards)
  127.     discounted_episode_rewards /= np.std(discounted_episode_rewards)
  128.     return discounted_episode_rewards
  129.  
  130.   def store_transition(self, s, a, r):
  131.     """
  132.        Store play memory for training
  133.        Arguments:
  134.            s: observation
  135.            a: action taken
  136.            r: reward after action
  137.    """
  138.     self.episode_observations.append(s)
  139.     self.episode_rewards.append(r)
  140.  
  141.     # Store actions as list of arrays
  142.     # e.g. for n_y = 2 -> [ array([ 1.,  0.]), array([ 0.,  1.]), array([ 0.,  1.]), array([ 1.,  0.]) ]
  143.     action = np.zeros(self.n_y)
  144.     action[a] = 1
  145.     self.episode_actions.append(action)
  146.  
  147.   def choose_action(self, observation):
  148.     """
  149.        Choose action based on observation
  150.        Arguments:
  151.            observation: array of state, has shape (num_features)
  152.        Returns: index of action we want to choose
  153.    """
  154.     # Reshape observation to (num_features, 1)
  155.     observation = observation[:, np.newaxis]
  156.  
  157.     # Run forward propagation to get softmax probabilities
  158.     prob_weights = self.sess.run(self.outputs_softmax, feed_dict={self.X: observation})
  159.  
  160.     # Select action using a biased sample
  161.     # this will return the index of the action we've sampled
  162.     action = np.random.choice(range(len(prob_weights.ravel())), p=prob_weights.ravel())
  163.     return action
  164.  
  165.   def learn(self):
  166.     # Discount and normalize episode reward
  167.     discounted_episode_rewards_norm = self.discount_and_norm_rewards()
  168.  
  169.     # Train on episode
  170.     self.sess.run(self.train_op, feed_dict={
  171.       self.X: np.vstack(self.episode_observations).T,
  172.       self.Y: np.vstack(np.array(self.episode_actions)).T,
  173.       self.discounted_episode_rewards_norm: discounted_episode_rewards_norm,
  174.     })
  175.  
  176.     # Reset the episode data
  177.     self.episode_observations, self.episode_actions, self.episode_rewards = [], [], []
  178.  
  179.     # Save checkpoint
  180.     if self.save_path is not None:
  181.       save_path = self.saver.save(self.sess, self.save_path)
  182.       print("Model saved in file: %s" % save_path)
  183.  
  184.     return discounted_episode_rewards_norm
  185.  
  186.  
  187. if __name__ == "__main__":
  188.  
  189.     PG = PolicyGradient(
  190.         n_x = env.observation_space.shape[0],
  191.         n_y = env.action_space.n,
  192.         learning_rate=0.02,
  193.         reward_decay=0.99
  194.     )
  195.  
  196.  
  197.     for episode in range(EPISODES):
  198.  
  199.         observation = env.reset()
  200.         episode_reward = 0
  201.  
  202.         while True:
  203.             if RENDER_ENV: env.render()
  204.  
  205.             # 1. Choose an action based on observation
  206.             action = PG.choose_action(observation)
  207.  
  208.             # 2. Take action in the environment
  209.             observation_, reward, done, info = env.step(action)
  210.  
  211.             # 4. Store transition for training
  212.             PG.store_transition(observation, action, reward)
  213.  
  214.             if done:
  215.                 episode_rewards_sum = sum(PG.episode_rewards)
  216.                 rewards.append(episode_rewards_sum)
  217.                 max_reward_so_far = np.amax(rewards)
  218.  
  219.                 print("==========================================")
  220.                 print("Episode: ", episode)
  221.                 print("Reward: ", episode_rewards_sum)
  222.                 print("Max reward so far: ", max_reward_so_far)
  223.  
  224.                 # 5. Train neural network
  225.                 discounted_episode_rewards_norm = PG.learn()
  226.  
  227.                 if max_reward_so_far > RENDER_REWARD_MIN: RENDER_ENV = True
  228.  
  229.  
  230.                 break
  231.  
  232.             # Save new observation
  233.             observation = observation_
Advertisement
Add Comment
Please, Sign In to add comment