basic_operations.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. '''
  2. Basic Operations example using TensorFlow library.
  3. Author: Aymeric Damien
  4. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  5. '''
  6. import tensorflow as tf
  7. # Basic constant operations
  8. # The value returned by the constructor represents the output
  9. # of the Constant op.
  10. a = tf.constant(2)
  11. b = tf.constant(3)
  12. # Launch the default graph.
  13. with tf.Session() as sess:
  14. print "a=2, b=3"
  15. print "Addition with constants: %i" % sess.run(a+b)
  16. print "Multiplication with constants: %i" % sess.run(a*b)
  17. # Basic Operations with variable as graph input
  18. # The value returned by the constructor represents the output
  19. # of the Variable op. (define as input when running session)
  20. # tf Graph input
  21. a = tf.placeholder(tf.int16)
  22. b = tf.placeholder(tf.int16)
  23. # Define some operations
  24. add = tf.add(a, b)
  25. mul = tf.mul(a, b)
  26. # Launch the default graph.
  27. with tf.Session() as sess:
  28. # Run every operation with variable input
  29. print "Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3})
  30. print "Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3})
  31. # ----------------
  32. # More in details:
  33. # Matrix Multiplication from TensorFlow official tutorial
  34. # Create a Constant op that produces a 1x2 matrix. The op is
  35. # added as a node to the default graph.
  36. #
  37. # The value returned by the constructor represents the output
  38. # of the Constant op.
  39. matrix1 = tf.constant([[3., 3.]])
  40. # Create another Constant that produces a 2x1 matrix.
  41. matrix2 = tf.constant([[2.],[2.]])
  42. # Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
  43. # The returned value, 'product', represents the result of the matrix
  44. # multiplication.
  45. product = tf.matmul(matrix1, matrix2)
  46. # To run the matmul op we call the session 'run()' method, passing 'product'
  47. # which represents the output of the matmul op. This indicates to the call
  48. # that we want to get the output of the matmul op back.
  49. #
  50. # All inputs needed by the op are run automatically by the session. They
  51. # typically are run in parallel.
  52. #
  53. # The call 'run(product)' thus causes the execution of threes ops in the
  54. # graph: the two constants and matmul.
  55. #
  56. # The output of the op is returned in 'result' as a numpy `ndarray` object.
  57. with tf.Session() as sess:
  58. result = sess.run(product)
  59. print result
  60. # ==> [[ 12.]]