How to find the gradient automatically in Tensorflow2.0
Tensorflow2.0 how to automatically find the gradient, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
For a given function: y (w) = aw ^ 2 + bw+c
Mathematical derivation: dy/dw=2aw+b
Then, dy/dw=2 * 1 * 4 + 2 * 4) = (1 ~ 2 ~ 2 ~ 3 ~ 4)
In Tensorflow2.0, the gradient can be obtained automatically. The specific code is as follows:
Import tensorflow as tfa=tf.constant (1.) b=tf.constant (2.) c=tf.constant (3.) w=tf.constant (4.) with tf.GradientTape () as tape: # construct gradient environment tape.watch ([w]) # find the gradient for w and trace the list y=a*w**2+b*w+c # construct the objective function [dy_dw] = tape.gradient (y, [w]) # function y derive the derivative of print (dy_dw) # for w
Running result:
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.