NNSample01.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import tensorflow as tf
  2. from numpy.random import RandomState
  3. # define the size of a batch
  4. batch_size=4
  5. # define coefficient matrices
  6. w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
  7. w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
  8. # define place for input and output, use param 'None' in shape can make the placeholder more flexible
  9. x = tf.placeholder(tf.float32, shape=[None, 2], name="x-input")
  10. y_ = tf.placeholder(tf.float32, shape=[None, 1], name="y-input")
  11. # forward propagation
  12. a = tf.matmul(x, w1)
  13. y = tf.matmul(a, w2)
  14. # define loss function ( sigmoid : 1/1+exp(-x) ), cross_entropy and train_step
  15. y = tf.sigmoid(y)
  16. cross_entropy=-tf.reduce_mean(
  17. y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))
  18. + (1-y)*tf.log(tf.clip_by_value(1-y, 1e-10, 1.0)))
  19. train_step = tf.train.AdamOptimizer().minimize(cross_entropy)
  20. # create a simulated dataset with a random number generator
  21. rdm = RandomState(1)
  22. dataset_size = 1280
  23. X = rdm.rand(dataset_size, 2)
  24. Y = [[int(x1+x2<1)] for (x1, x2) in X]
  25. with tf.Session() as sess:
  26. sess.run(tf.global_variables_initializer())
  27. print w1.eval(session=sess)
  28. print sess.run(w2)
  29. # writer = tf.summary.FileWriter("logs", tf.get_default_graph())
  30. # set the number of iteration
  31. STEPS = 10000
  32. for i in range(STEPS):
  33. start = (i * batch_size) % dataset_size
  34. end = min(start+ batch_size, dataset_size)
  35. sess.run(train_step, feed_dict={x: X[start: end], y_: Y[start: end]})
  36. if i%1000==0:
  37. # calculate cross entropy with some interval
  38. total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y})
  39. print ("after %d training step(s), cross entropy on all data is %g." % (i, total_cross_entropy))
  40. # tf.summary.histogram("iteration-w1", w1)
  41. # tf.summary.histogram("iteration-w2", w2)
  42. print sess.run(w1)
  43. print sess.run(w2)
  44. # writer.close()