Python TensorFlow ``GradientTape.stop_recording()`` 方法详解与实例


发布日期 : 2021-03-25 18:48:41 UTC

访问量: 10 次浏览

Python – tensorflow.GradientTape.stop\_recording()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

stop\_recording()是用来暂时停止录音操作的。如果磁带没有记录,它将引发一个错误。

语法:
tensorflow.GradientTape.stop_recording()

参数:
它不接受任何参数。

返回值:
None

抛出:

  • RunTimeError:如果磁带目前没有记录,它将引发RunTimeError。

示例 1:

# Importing the library
import tensorflow as tf

x = tf.constant(4.0)

# Using GradientTape
with tf.GradientTape() as gfg:
  gfg.watch(x)

  # Stop recording
  with gfg.stop_recording():
    y = x * x * x

# Computing gradient
res = gfg.gradient(y, x) 

# Printing result
print("res: ", res)

输出:

res: None

示例 2:

# Importing the library
import tensorflow as tf

x = tf.constant(4.0)

# Using GradientTape
with tf.GradientTape() as gfg:
  gfg.watch(x)

  # Stop recording
  with gfg.stop_recording():
    y = x * x * x

  # Starting the recording again
  gfg.watch(x)
  y = x * x

# Computing gradient
res = gfg.gradient(y, x) 

# Printing result
print("res: ", res)

输出:

res: tf.Tensor(8.0, shape=(), dtype=float32)