直接上代码,一看就明白!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import tensorflow as tf import numpy as np
v1=tf.Variable(tf.random.normal(shape=[4,3],mean=0,stddev=1))
a = np.random.random((3,3))
v2=tf.constant(a.astype('float32'))
v3=tf.Variable(a.astype('float32'))
v4=tf.Variable(v2)
v5=tf.Variable(tf.ones([4,3]))
v6=tf.convert_to_tensor(a,dtype=tf.float32)
with tf.GradientTape() as g: y = v2 * v2 dy_dx = g.gradient(y, v2) print(dy_dx)
with tf.GradientTape() as g: g.watch(v2) y = v2 * v2 dy_dx = g.gradient(y, v2) print(dy_dx)
with tf.GradientTape() as g: y = v4 * v4 dy_dx = g.gradient(y, v4) print(dy_dx)
|
-------------
Thank you for reading
-------------