当前位置:   article > 正文

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

tensorflow 动态图

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

import numpy as np
import tensorflow as tf
  • 1
  • 2

设置eager mode

tf.enable_eager_execution()
tfe = tf.contrib.eager
  • 1
  • 2

定义常量

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

不使用session执行前向传播

c = a + b
print("a + b = %i"%c)
d = a * b
print("a * b = %i"%d)
  • 1
  • 2
  • 3
  • 4
a + b = 5
a * b = 6
  • 1
  • 2

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

通过迭代的方式访问tensor

for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        print(a[i][j])
  • 1
  • 2
  • 3
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)
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52055
推荐阅读
相关标签
  

闽ICP备14008679号