0%

用Graphs的运行方式执行Eager模式的代码

一、在执行代码时使用 tf.enable_eager_execution() 开启eager模式

二、正向传播支持自定义class类型

  1. 定义的model继承keras.model
  2. init()里定义所用到的layer类型
  3. call()里连接layer,返回output

二、反向传播的使用

  1. 先用tf的api定义loss函数

  2. 用tfe的api调用loss得到梯度grads

    1
    2
    tfe.gradients_function(loss,x)
    tfe.implicit_gradients(loss)

    或者也可以采用GradientTape(y,x)来进行计算可以根据函数y计算变量x的梯

    1
    2
    with tf.GradientTape() as grad_tape:
    grad_tape.gradient(y,x)

    在tf的诸多eager execution样例中里用第二种方法较多

  3. 用tf定义的optimizer优化梯度更新参数

    1
    optimizer.apply_gradients(grad)

三、Eager的输入使用tf.data.Dataset但不支持placeholderstring_input_producer这类在graph模式中使用的输入

四、使用tf.train.Checkpoint()保存模型的checkpoint

五、可以使用tf.contrib.eager.defun对python的函数进行封装转换成图的形式进行运算。用eager的写法可以实现graph的运算速度。

  1. 使用了defun的forward propagation例子如下:

    1
    2
    model.call = tf.contrib.eager.defun(model.call)
    model(x, training=True) # executes a graph, with dropout
  2. 一个使用了defun的back propagation例子如下

    1
    2
    3
    4
    5
    6
    7
    optimizer = tf.train.GradientDescentOptimizer()
    with tf.GradientTape() as tape:
    outputs = model(x)
    gradient = tape.gradient(outputs, model.trainable_variables)
    defun_gradients = tfe.defun(gradient)
    tfe.defun(optimizer.apply_gradients((grad, var) for grad,
    var in zip(gradient,model.trainable_variables)))

    然而此后defun可能会被AutoGraph替代

Refer:Code with Eager Execution, Run with Graphs: Optimizing Your Code with RevNet as an Example