らんだむな記憶

blogというものを体験してみようか!的なー

積極的実行

英語のまま・・・

TensorFlowの“積極的実行”はグラフを構築することなく即座にオペレーションを評価する命令型プログラミング環境である。オペレーションは後ほど実行する計算グラフを構築する代わりに具体的な値を返却する。このことによってTensorFlowの使用が簡単になりモデルのデバッグも容易になる。またボイルプレートも減らすことができる。*1

セットアップと基本的な使い方

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf

tf.enable_eager_execution()

“積極的実行”を有効にすることでTensorFlowのオペレーションの挙動が変化する—オペレーションは値を即座に評価しPythonへと返却するようになる。

・・・と段々面倒になってきたところでTensorFlow 2.0 Alpha : ガイド : Eager Execution – TensorFlow 2.0 / 1.xに和訳があるのでこちらでOKということで。

MNIST For ML Beginnersこの頃のと比較すると良いんだろうなぁ。
適当に実行してみると、確かに何かしら変わっていることはわかる。

>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>> import tensorflow as tf
>>> a = tf.constant(3)
>>> b = tf.constant(7)
>>> a
<tf.Tensor 'Const_2:0' shape=() dtype=int32>
>>> add_op = tf.add(a, b)
>>> add_op
<tf.Tensor 'Add:0' shape=() dtype=int32>
>>> with tf.Session() as sess:
>>>     add_op_result = sess.run([add_op])
>>>     print(add_op_result, type(add_op_result))
[10] <class 'list'>
>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> a = tf.constant(3)
>>> b = tf.constant(7)
>>> a
<tf.Tensor: id=0, shape=(), dtype=int32, numpy=3>
>>> add_op = tf.add(a, b)
>>> add_op
<tf.Tensor: id=3, shape=(), dtype=int32, numpy=10>
>>> with tf.Session() as sess:
>>>     add_op_result = sess.run([add_op])
>>>     print(add_op_result, type(add_op_result))
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
...
RuntimeError: The Session graph is empty.  Add operations to the graph before calling run().

*1:と言われても初期のTensorFlowを知らないと何のこっちゃであるが・・・