Tensorflow2——Eager模式简介以及运用

TensorFlow的eager执行模式是一个重要的编程环境,它能立即评估运算,而无须构建图:运算会实时返回值,而不是构建一个计算图后再运行。这使得使用TensorFlow和调试模型更简单,并且可以减少很多样板代码。

eager执行模式对研究和实验来说是一个灵活的机器学习平台,有下列特点:

  • ·一个更符合直觉的接口:以自然的方式组织代码并可以应用Python数据结构。快速地遍历小的模型和小量数据。
  • ·更易调试:直接调用运算来检查运行的模型和测试变化。用标准的Python调试工具来快速报告错误。
  • ·自然的控制流:使用Python控制流取代图控制流,简化动态模型的配置。
import tensorflow as tf


def multiply(x, y):
    """Matrix multiplication.
    Note: it requires the input shape of both input to match.
    Args:
        x: tf.Tensor a matrix
        y: tf.Tensor a matrix
    Returns:
        The matrix multiplcation x @ y
    """

    assert x.shape == y.shape
    return tf.matmul(x, y)


def add(x, y):
    """Add two tensors.
    Args:
        x: the left hand operand.
        y: the right hand operand. It should be compatible with x.
    Returns:
        x + y
    """
    return x + y


def main():
    """Main program."""
    A = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
    x = tf.constant([[0, 10], [0, 0.5]])
    b = tf.constant([[1, -1]], dtype=tf.float32)

    z = multiply(A, x)
    y = add(z, b)
    print(y)


if __name__ == "__main__":
    main()

GradientTape

tf.GradientTape()函数创建一个记录所有自动微分运算的上下文(“磁带”)。如果上下文管理器中至少有一个输入是可监控的,而且正在被监控,那么每个在上下文管理器中执行的运算都会被记录在“磁带”上。

当出现下列情况时,输入是可监控的:

  • ·它是一个由tf.Variable创建的可训练变量。
  • ·它正被“磁带”监视,这个可以通过调用tf.Tensor对象的watch方法实现。
import tensorflow as tf
"""
一旦tf.GradientTape.gradient()被调用,tf.GradientTape对象(即所谓的“磁带”)就会释放它保存的全部资源。
在大多数情况下这是我们想要的,但是有的情况下我们需要多次调用tf.GradientTape.gradient()。
这时,我们需要创建一个持久性的梯度“磁带”,它能够允许多次gradient方法的调用而不释放资源。这种情况下交由开发者负责资源的释放
"""
x = tf.Variable(4.0)
y = tf.Variable(2.0)
with tf.GradientTape(persistent=True) as tape:
    z = x + y
    w = tf.pow(x, 2)
dz_dy = tape.gradient(z, y)
dz_dx = tape.gradient(z, x)
dw_dx = tape.gradient(w, x)
print(dz_dy, dz_dx, dw_dx)
# Release the resources
del tape
import tensorflow as tf

x = tf.constant(4.0)
with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.pow(x, 2)
# Will compute 8 = 2*x, x = 8
dy_dx = tape.gradient(y, x)
print(dy_dx)

猜你喜欢

转载自blog.csdn.net/qq_40107571/article/details/131350967