tensorflow-底层梯度(2)

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018
@author: myhaspl
"""

import tensorflow as tf
x = tf.constant(1.)
a = 12*x
b = 2*a
c = 3*b
g1 = tf.gradients([a + b + c], [a, b, c])
g2 = tf.gradients([a + b + c], [a, b, c],stop_gradients=[a, b, c])

sess=tf.Session()
with sess:

    print sess.run(g1)
    print sess.run(g2)

[9.0, 4.0, 1.0]
[1.0, 1.0, 1.0]
与全导数g1 = tf.gradients([a + b + c], [a, b, c])相比,偏导数g2 = tf.gradients([a + b + c], [a, b, c],stop_gradients=[a, b, c])
的值是[1.0,1.0 , 1.0],而全导数g1 = tf.gradients([a + b + c], [a, b, c])考虑了a对b和c的影响,并求值为[9.0, 4.0, 1.0],例如:

(a+b+c)'a=9,其中:

b=2*a

c=3b=32*a=6a

相比于在图构造期间使用的tf.stop_gradient。stop_gradients提供了已经构造完图之后停止梯度的方法,当将这两种方法结合起来时,反向传播在tf.stop_gradient节点和stop_gradients节点处都停止,无论首先遇到哪个节点。

猜你喜欢

转载自blog.51cto.com/13959448/2330673