美文网首页
tf.stop_gradient

tf.stop_gradient

作者: help_youself | 来源:发表于2021-02-21 08:47 被阅读0次

gradient.py

#https://blog.csdn.net/hustqb/article/details/80260002
import numpy as np
import tensorflow.compat.v1 as tf
if __name__ == '__main__':
    tf.compat.v1.disable_eager_execution()
    session = tf.Session()
    x_input = tf.placeholder(tf.float32, name='x_input')
    y_input = tf.placeholder(tf.float32, name='y_input')
    w = tf.Variable(2.0, name='weight')
    b = tf.Variable(1.0, name='biases')
    y = tf.add(tf.multiply(x_input, w), b)
    f1 =y-y_input
    gradients_node = tf.gradients(f1, w)
    init = tf.global_variables_initializer()
    session.run(init)
    in1=np.array([5.0])
    in2=np.array([10.0])
    result = session.run(gradients_node, feed_dict={x_input:in1,y_input:in2})
    print (result)
    y1=2*y
    f2 =y-y1
    gradients_node = tf.gradients(f2, w)
    result = session.run(gradients_node, feed_dict={x_input:in1})
    print (result)
    y2=3*y
    f3 =y-tf.stop_gradient(y2)
    gradients_node = tf.gradients(f3, w)
    result = session.run(gradients_node, feed_dict={x_input:in1})
    print (result)
    y3=4*y
    y4=tf.placeholder(tf.float32, name='y4_input')
    f4=y-y4
    gradients_node = tf.gradients(f4, w)
    y3_result=session.run(y3,feed_dict={x_input:in1})
    result = session.run(gradients_node, feed_dict={x_input:in1,y4:y3_result})
    print (result)
    session.close()

y=w*x+b
f1=y-y\_input
y1=2*y
f2=y-y1=-y
tf.stop\_gradient(y\_input). When executed in a graph, the op tf.stop_gradient outputs its input tensor as-is.
y2=3*y
f3=y-tf.stop\_gradient(y2)
 Hence,
\frac{\partial f1}{\partial w}=x\_input
\frac{\partial f2}{\partial w}=-x\_input
\frac{\partial f3}{\partial w}=x\_input
Result:
[5.0]
[-5.0]
[5.0]

相关文章

  • tf.stop_gradient

    gradient.py      . When executed in a graph, the op tf.st...

网友评论

      本文标题:tf.stop_gradient

      本文链接:https://www.haomeiwen.com/subject/rqiffltx.html