basic_eager_api.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. '''
  2. Basic introduction to TensorFlow's Eager API.
  3. Author: Aymeric Damien
  4. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  5. What is Eager API?
  6. " Eager execution is an imperative, define-by-run interface where operations are
  7. executed immediately as they are called from Python. This makes it easier to
  8. get started with TensorFlow, and can make research and development more
  9. intuitive. A vast majority of the TensorFlow API remains the same whether eager
  10. execution is enabled or not. As a result, the exact same code that constructs
  11. TensorFlow graphs (e.g. using the layers API) can be executed imperatively
  12. by using eager execution. Conversely, most models written with Eager enabled
  13. can be converted to a graph that can be further optimized and/or extracted
  14. for deployment in production without changing code. " - Rajat Monga
  15. '''
  16. from __future__ import absolute_import, division, print_function
  17. import numpy as np
  18. import tensorflow as tf
  19. import tensorflow.contrib.eager as tfe
  20. # Set Eager API
  21. print("Setting Eager mode...")
  22. tfe.enable_eager_execution()
  23. # Define constant tensors
  24. print("Define constant tensors")
  25. a = tf.constant(2)
  26. print("a = %i" % a)
  27. b = tf.constant(3)
  28. print("b = %i" % b)
  29. # Run the operation without the need for tf.Session
  30. print("Running operations, without tf.Session")
  31. c = a + b
  32. print("a + b = %i" % c)
  33. d = a * b
  34. print("a * b = %i" % d)
  35. # Full compatibility with Numpy
  36. print("Mixing operations with Tensors and Numpy Arrays")
  37. # Define constant tensors
  38. a = tf.constant([[2., 1.],
  39. [1., 0.]], dtype=tf.float32)
  40. print("Tensor:\n a = %s" % a)
  41. b = np.array([[3., 0.],
  42. [5., 1.]], dtype=np.float32)
  43. print("NumpyArray:\n b = %s" % b)
  44. # Run the operation without the need for tf.Session
  45. print("Running operations, without tf.Session")
  46. c = a + b
  47. print("a + b = %s" % c)
  48. d = tf.matmul(a, b)
  49. print("a * b = %s" % d)
  50. print("Iterate through Tensor 'a':")
  51. for i in range(a.shape[0]):
  52. for j in range(a.shape[1]):
  53. print(a[i][j])