basic_operations.py 2.3 KB

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