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()
. When executed in a graph, the op tf.stop_gradient outputs its input tensor as-is.
Hence,
Result:
[5.0]
[-5.0]
[5.0]
网友评论