tf.GradientTape 无法在 'with' 街区外观看

tf.GradientTape can't watch outside 'with' block

tensorflow.org 上的 TensorFlow 教程展示了如何使用 tf.GradientTape 作为:

x = tf.convert_to_tensor([1,2,3]);
with tf.GradientTape() as t:
  t.watch(x); 

我想知道为什么我不能像这样将 t.watch(x) 移动到 with 块之外:

x = tf.convert_to_tensor([1,2,3]);
t = tf.GradientTape();
t.watch(x); #ERROR

错误是:

tape.py (59):
pywrap_tensorflow.TFE_Py_TapeWatch(tape._tape, tensor)

AttributeError: 'NoneType' object has no attribute '_tape'

我知道怎么做了。 tf.GradientTape class 旨在在 with 块内工作,即。它有 enterexit 方法。

所以要让它在 'with' 块之外工作,必须显式调用方法 __enter__,但是,避免直接调用 __enter__

x = tf.convert_to_tensor([1,2,3]);
t = tf.GradientTape();
t.__enter__();
t.watch(x); 

参考: Explaining Python's '__enter__' and '__exit__'