TensorFlow-Examples - basic_eager_api.py

https://github.com/aymericdamien/TensorFlow-Examples

1. basic_eager_api.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# from __future__ import absolute_import, division, print_function

'''
Basic introduction to TensorFlow's Eager API.
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe

# Set Eager API
print("Setting Eager mode...")
tfe.enable_eager_execution()

# Define constant tensors
print("Define constant tensors")
a = tf.constant(2)
print("a = %i" % a)
b = tf.constant(3)
print("b = %i" % b)

# Run the operation without the need for tf.Session
print("Running operations, without tf.Session")
c = a + b
print("a + b = %i" % c)
d = a * b
print("a * b = %i" % d)

# Full compatibility with Numpy
print("Mixing operations with Tensors and Numpy Arrays")

# Define constant tensors
a = tf.constant([[2., 1.],
                 [1., 0.]], dtype=tf.float32)
print("Tensor:\n a = %s" % a)
b = np.array([[3., 0.],
              [5., 1.]], dtype=np.float32)
print("NumpyArray:\n b = %s" % b)

# Run the operation without the need for tf.Session
print("Running operations, without tf.Session")

c = a + b
print("a + b = %s" % c)

d = tf.matmul(a, b)
print("a * b = %s" % d)

print("Iterate through Tensor 'a':")
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        print(a[i][j])

2. What is Eager API?

Eager execution is an imperative, define-by-run interface where operations are executed immediately as they are called from Python. This makes it easier to get started with TensorFlow, and can make research and development more intuitive. A vast majority of the TensorFlow API remains the same whether eager execution is enabled or not. As a result, the exact same code that constructs TensorFlow graphs (e.g. using the layers API) can be executed imperatively by using eager execution. Conversely, most models written with Eager enabled can be converted to a graph that can be further optimized and/or extracted for deployment in production without changing code.
即刻执行是一个必要的,定义运行的接口,其中操作在从 Python 调用时立即执行。这使得 TensorFlow 开始使用变得更容易,并且可以使研究和开发更加直观。无论是否启用了即刻执行,绝大多数 TensorFlow API 都保持不变。通过使用即刻执行,可以强制执行构造 TensorFlow 图的完全相同的代码 (e.g. using the layers API)。相反,大多数使用 Eager 编写的模型都可以转换为可以进一步优化和/或提取的图形,以便在不更改代码的情况下在生产中进行部署。

eager ['iːgə]:adj. 渴望的,热切的,热心的
imperative [ɪm'perətɪv]:adj. 必要的,不可避免的,紧急的,命令的,专横的,势在必行的,祈使的 n. 必要的事,命令,需要,规则,祈使语气
intuitive [ɪn'tjuːɪtɪv]:adj. 直觉的,凭直觉获知的
majority [mə'dʒɒrɪtɪ]:n. 多数,成年
vast [vɑːst]:adj. 广阔的,巨大的,大量的,巨额的 n. 浩瀚,广阔无垠的空间
exact [ɪg'zækt; eg-]:adj. 准确的,精密的,精确的 vt. 要求,强求,急需 vi. 勒索钱财
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐