您好,登錄后才能下訂單哦!
1. 函數求一階導
import tensorflow as tf tf.enable_eager_execution() tfe=tf.contrib.eager from math import pi def f(x): return tf.square(tf.sin(x)) assert f(pi/2).numpy()==1.0 sess=tf.Session() grad_f=tfe.gradients_function(f) print(grad_f(np.zeros(1))[0].numpy())
2. 高階函數求導
import numpy as np def f(x): return tf.square(tf.sin(x)) def grad(f): return lambda x:tfe.gradients_function(f)(x)[0] x=tf.lin_space(-2*pi,2*pi,100) # print(grad(f)(x).numpy()) x=x.numpy() import matplotlib.pyplot as plt plt.plot(x,f(x).numpy(),label="f") plt.plot(x,grad(f)(x).numpy(),label="first derivative")#一階導 plt.plot(x,grad(grad(f))(x).numpy(),label="second derivative")#二階導 plt.plot(x,grad(grad(grad(f)))(x).numpy(),label="third derivative")#三階導 plt.legend() plt.show() def f(x,y): output=1 for i in range(int(y)): output=tf.multiply(output,x) return output def g(x,y): return tfe.gradients_function(f)(x,y)[0] print(f(3.0,2).numpy()) #f(x)=x^2 print(g(3.0,2).numpy()) #f'(x)=2*x print(f(4.0,3).numpy())#f(x)=x^3 print(g(4.0,3).numpy())#f(x)=3x^2
3. 函數求一階偏導
x=tf.ones((2,2)) with tf.GradientTape(persistent=True) as t: t.watch(x) y=tf.reduce_sum(x) z=tf.multiply(y,y) dz_dy=t.gradient(z,y) print(dz_dy.numpy()) dz_dx=t.gradient(z,x) print(dz_dx.numpy()) for i in [0, 1]: for j in [0, 1]: print(dz_dx[i][j].numpy() )
4. 函數求二階偏導
x=tf.constant(2.0) with tf.GradientTape() as t: with tf.GradientTape() as t2: t2.watch(x) y=x*x*x dy_dx=t2.gradient(y,x) d2y_dx2=t.gradient(dy_dx,x) print(dy_dx.numpy()) print(d2y_dx2.numpy())
以上這篇tensorflow求導和梯度計算實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。