tensorflow求導(dǎo)和梯度計(jì)算實(shí)例
1. 函數(shù)求一階導(dǎo)
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. 高階函數(shù)求導(dǎo)
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")#一階導(dǎo) plt.plot(x,grad(grad(f))(x).numpy(),label="second derivative")#二階導(dǎo) plt.plot(x,grad(grad(grad(f)))(x).numpy(),label="third derivative")#三階導(dǎo) 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. 函數(shù)求一階偏導(dǎo)
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. 函數(shù)求二階偏導(dǎo)
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求導(dǎo)和梯度計(jì)算實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
pytorch如何保存訓(xùn)練模型參數(shù)并實(shí)現(xiàn)繼續(xù)訓(xùn)練
這篇文章主要介紹了pytorch如何保存訓(xùn)練模型參數(shù)并實(shí)現(xiàn)繼續(xù)訓(xùn)練問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09python3中@dataclass的實(shí)現(xiàn)示例
@dataclass?是 Python 3.7 引入的一個(gè)裝飾器,用于方便地定義符合數(shù)據(jù)類協(xié)議的類,本文主要介紹了python3中@dataclass的實(shí)現(xiàn)示例,感興趣的可以了解一下2024-02-02Pyhton自動(dòng)化測(cè)試持續(xù)集成和Jenkins
這篇文章介紹了Pyhton自動(dòng)化測(cè)試持續(xù)集成和Jenkins,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07python語(yǔ)言元素知識(shí)點(diǎn)詳解
在本篇文章中小編給大家分享了關(guān)于python語(yǔ)言元素的相關(guān)知識(shí)點(diǎn)以及實(shí)例代碼,需要的朋友們跟著學(xué)習(xí)下。2019-05-05Python爬取十篇新聞統(tǒng)計(jì)TF-IDF
這篇文章主要為大家詳細(xì)介紹了Python爬取十篇新聞統(tǒng)計(jì)TF-IDF的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01