Guest User

Untitled

a guest
Oct 21st, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.94 KB | None | 0 0
  1. from __future__ import print_function, division
  2. import numpy as np
  3. import tensorflow as tf
  4. import matplotlib.pyplot as plt
  5.  
  6. num_epochs = 100
  7. total_series_length = 50000
  8. truncated_backprop_length = 15
  9. state_size = 4
  10. num_classes = 2
  11. echo_step = 3
  12. batch_size = 5
  13. num_batches = total_series_length//batch_size//truncated_backprop_length
  14. num_layers = 3
  15.  
  16. def generateData():
  17. x = np.array(np.random.choice(2, total_series_length, p=[0.5, 0.5]))
  18. y = np.roll(x, echo_step)
  19. y[0:echo_step] = 0
  20.  
  21. x = x.reshape((batch_size, -1)) # The first index changing slowest, subseries as rows
  22. y = y.reshape((batch_size, -1))
  23.  
  24. return (x, y)
  25.  
  26. batchX_placeholder = tf.placeholder(tf.float32, [batch_size, truncated_backprop_length])
  27. batchY_placeholder = tf.placeholder(tf.int32, [batch_size, truncated_backprop_length])
  28.  
  29. init_state = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])
  30.  
  31. state_per_layer_list = tf.unpack(init_state, axis=0)
  32. rnn_tuple_state = tuple(
  33. [tf.nn.rnn_cell.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1])
  34. for idx in range(num_layers)]
  35. )
  36.  
  37. W2 = tf.Variable(np.random.rand(state_size, num_classes),dtype=tf.float32)
  38. b2 = tf.Variable(np.zeros((1,num_classes)), dtype=tf.float32)
  39.  
  40. # Unpack columns
  41. inputs_series = tf.split(1, truncated_backprop_length, batchX_placeholder)
  42. labels_series = tf.unpack(batchY_placeholder, axis=1)
  43.  
  44. # Forward passes
  45. cell = tf.nn.rnn_cell.LSTMCell(state_size, state_is_tuple=True)
  46. cell = tf.nn.rnn_cell.MultiRNNCell([cell] * num_layers, state_is_tuple=True)
  47. states_series, current_state = tf.nn.rnn(cell, inputs_series, initial_state=rnn_tuple_state)
  48.  
  49. logits_series = [tf.matmul(state, W2) + b2 for state in states_series] #Broadcasted addition
  50. predictions_series = [tf.nn.softmax(logits) for logits in logits_series]
  51.  
  52. losses = [tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels) for logits, labels in zip(logits_series,labels_series)]
  53. total_loss = tf.reduce_mean(losses)
  54.  
  55. train_step = tf.train.AdagradOptimizer(0.3).minimize(total_loss)
  56.  
  57. def plot(loss_list, predictions_series, batchX, batchY):
  58. plt.subplot(2, 3, 1)
  59. plt.cla()
  60. plt.plot(loss_list)
  61.  
  62. for batch_series_idx in range(5):
  63. one_hot_output_series = np.array(predictions_series)[:, batch_series_idx, :]
  64. single_output_series = np.array([(1 if out[0] < 0.5 else 0) for out in one_hot_output_series])
  65.  
  66. plt.subplot(2, 3, batch_series_idx + 2)
  67. plt.cla()
  68. plt.axis([0, truncated_backprop_length, 0, 2])
  69. left_offset = range(truncated_backprop_length)
  70. plt.bar(left_offset, batchX[batch_series_idx, :], width=1, color="blue")
  71. plt.bar(left_offset, batchY[batch_series_idx, :] * 0.5, width=1, color="red")
  72. plt.bar(left_offset, single_output_series * 0.3, width=1, color="green")
  73.  
  74. plt.draw()
  75. plt.pause(0.0001)
  76.  
  77.  
  78. with tf.Session() as sess:
  79. sess.run(tf.initialize_all_variables())
  80. plt.ion()
  81. plt.figure()
  82. plt.show()
  83. loss_list = []
  84.  
  85. for epoch_idx in range(num_epochs):
  86. x,y = generateData()
  87.  
  88. _current_state = np.zeros((num_layers, 2, batch_size, state_size))
  89.  
  90. print("New data, epoch", epoch_idx)
  91.  
  92. for batch_idx in range(num_batches):
  93. start_idx = batch_idx * truncated_backprop_length
  94. end_idx = start_idx + truncated_backprop_length
  95.  
  96. batchX = x[:,start_idx:end_idx]
  97. batchY = y[:,start_idx:end_idx]
  98.  
  99. _total_loss, _train_step, _current_state, _predictions_series = sess.run(
  100. [total_loss, train_step, current_state, predictions_series],
  101. feed_dict={
  102. batchX_placeholder: batchX,
  103. batchY_placeholder: batchY,
  104. init_state: _current_state
  105. })
  106.  
  107.  
  108. loss_list.append(_total_loss)
  109.  
  110. if batch_idx%100 == 0:
  111. print("Step",batch_idx, "Batch loss", _total_loss)
  112. plot(loss_list, _predictions_series, batchX, batchY)
  113.  
  114. plt.ioff()
  115. plt.show()
Add Comment
Please, Sign In to add comment