1. 程式人生 > >(tensorflow之二十)TensorFlow Eager Execution立即執行外掛

(tensorflow之二十)TensorFlow Eager Execution立即執行外掛

一、安裝

有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