欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【TensorFlow】:Eager Mode(动态图模式)

程序员文章站 2022-03-09 20:23:15
...

TensorFlow的Eager模型,也可以看做是动态图模型。该模型下不需要先构造图,然后再使用Session.run(),而是可以得到即时的反馈。这样在研究和开发时会更加符合直觉。

import numpy as np
import tensorflow as tf

设置eager mode

tf.enable_eager_execution()
tfe = tf.contrib.eager

定义常量

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

不使用session执行前向传播

c = a + b
print("a + b = %i"%c)
d = a * b
print("a * b = %i"%d)
a + b = 5
a * b = 6

与numpy兼容

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)
# tenosr与NumpyArray混合操作
c = a + b
print("a + b = %s"%c)
d = tf.matmul(a,b)
print("a * b = %s"%d)
Tensor:
 a = tf.Tensor(
[[2. 1.]
 [1. 0.]], shape=(2, 2), dtype=float32)
NumpyArray:
 b = [[3. 0.]
 [5. 1.]]
a + b = tf.Tensor(
[[5. 1.]
 [6. 1.]], shape=(2, 2), dtype=float32)
a * b = tf.Tensor(
[[11.  1.]
 [ 3.  0.]], shape=(2, 2), dtype=float32)

通过迭代的方式访问tensor

for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        print(a[i][j])
tf.Tensor(2.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(0.0, shape=(), dtype=float32)