(tensorflow之二十)TensorFlow Eager Execution立即执行插件
程序员文章站
2024-01-19 09:18:04
...
一、安装
有GPU的安装
docker pull tensorflow/tensorflow:nightly-gpu
docker run --runtime=nvidia -it -p 8888:8888 tensorflow/tensorflow:nightly-gpu
无GPU的安装
docker pull tensorflow/tensorflow:nightly
docker run -it -p 8888:8888 tensorflow/tensorflow:nightly
二、起动Eager Execution
import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
三、示例
x = tf.matmul([[1, 2],
[3, 4]],
[[4, 5],
[6, 7]])
y = tf.add(x, 1)
z = tf.random_uniform([5, 3])
print(x)
print(y)
print(z)
与流数据不同的时,这时不需通过tf.Session().run()进行运算,可以直接对数据进行计算;
运算结果如下:
tf.Tensor(
[[16 19]
[36 43]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[17 20]
[37 44]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[ 0.25058532 0.0929395 0.54113817]
[ 0.3108716 0.93350542 0.84909797]
[ 0.53081679 0.12788558 0.01767385]
[ 0.29725885 0.33540785 0.83588314]
[ 0.38877153 0.39720535 0.78914213]], shape=(5, 3), dtype=float32)
Eager Execution可以实现在Numpy的无缝衔接
例:
import numpy as np
np_x = np.array(2., dtype=np.float32)
x = tf.constant(np_x)
py_y = 3.
y = tf.constant(py_y)
z = x + y + 1
print(z)
print(z.numpy())
运算结果如下:
tf.Tensor(6.0, shape=(), dtype=float32)
6.0