Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. import tensorflow as tf
  2.  
  3.  
  4. #####################
  5. # preparation stuff #
  6. #####################
  7.  
  8. # define input and output data
  9. input_data = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]  # XOR input
  10. output_data = [0., 1., 1., 0.]  # XOR output
  11.  
  12. # create a placeholder for the input
  13. # None indicates a variable batch size for the input
  14. # one input's dimension is [1, 2]
  15. n_input = tf.placeholder(tf.float32, shape=[None, 2])
  16.  
  17. # number of neurons in the hidden layer
  18. hidden_nodes = 5
  19.  
  20.  
  21. ################
  22. # hidden layer #
  23. ################
  24. b_hidden = tf.Variable(0.1)  # hidden layer's bias neuron
  25. W_hidden = tf.Variable(tf.random_uniform([hidden_nodes, 2], -1.0, 1.0))  # hidden layer's weight matrix
  26.                                                                          # initialized with a uniform distribution
  27. hidden = tf.sigmoid(tf.matmul(W_hidden, n_input) + b_hidden)  # calc hidden layer's activation
  28.  
  29.  
  30. ################
  31. # output layer #
  32. ################
  33. W_output = tf.Variable(tf.random_uniform([hidden_nodes, 1], -1.0, 1.0))  # output layer's weight matrix
  34. output = tf.sigmoid(tf.matmul(W_output, hidden))  # calc output layer's activation
  35.  
  36.  
  37. ############
  38. # learning #
  39. ############
  40. cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(output, n_input)  # calc cross entropy between current
  41.                                                                           # output and desired output
  42. loss = tf.reduce_mean(cross_entropy)  # mean the cross_entropy
  43. optimizer = tf.train.GradientDescentOptimizer(0.1)  # take a gradient descent for optimizing with a "stepsize" of 0.1
  44. train = optimizer.minimize(loss)  # let the optimizer train
  45.  
  46.  
  47. ####################
  48. # initialize graph #
  49. ####################
  50. init = tf.initialize_all_variables()
  51.  
  52. sess = tf.Session()  # create the session and therefore the graph
  53. sess.run(init)  # initialize all variables
  54.  
  55. # train the network
  56. for epoch in xrange(0, 201):
  57.     sess.run(train)  # run the training operation
  58.     if epoch % 20 == 0:
  59.         print("step: {:>3} | W: {} | b: {}".format(epoch, sess.run(W_hidden), sess.run(b_hidden)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement