TensorFlow梯度求解tf.gradients實(shí)例
我就廢話不多說了,直接上代碼吧!
import tensorflow as tf w1 = tf.Variable([[1,2]]) w2 = tf.Variable([[3,4]]) res = tf.matmul(w1, [[2],[1]]) grads = tf.gradients(res,[w1]) with tf.Session() as sess: tf.global_variables_initializer().run() print sess.run(res) print sess.run(grads)
輸出結(jié)果為:
[[4]] [array([[2, 1]], dtype=int32)]
可以這樣看res與w1有關(guān),w1的參數(shù)設(shè)為[a1,a2],則:
2*a1 + a2 = res
所以res對(duì)a1,a2求導(dǎo)可得 [[2,1]]為w1對(duì)應(yīng)的梯度信息。
import tensorflow as tf def gradient_clip(gradients, max_gradient_norm): """Clipping gradients of a model.""" clipped_gradients, gradient_norm = tf.clip_by_global_norm( gradients, max_gradient_norm) gradient_norm_summary = [tf.summary.scalar("grad_norm", gradient_norm)] gradient_norm_summary.append( tf.summary.scalar("clipped_gradient", tf.global_norm(clipped_gradients))) return clipped_gradients w1 = tf.Variable([[3.0,2.0]]) # w2 = tf.Variable([[3,4]]) params = tf.trainable_variables() res = tf.matmul(w1, [[3.0],[1.]]) opt = tf.train.GradientDescentOptimizer(1.0) grads = tf.gradients(res,[w1]) clipped_gradients = gradient_clip(grads,2.0) global_step = tf.Variable(0, name='global_step', trainable=False) #update = opt.apply_gradients(zip(clipped_gradients,params), global_step=global_step) with tf.Session() as sess: tf.global_variables_initializer().run() print sess.run(res) print sess.run(grads) print sess.run(clipped_gradients)
以上這篇TensorFlow梯度求解tf.gradients實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- tensorflow 實(shí)現(xiàn)自定義梯度反向傳播代碼
- 有關(guān)Tensorflow梯度下降常用的優(yōu)化方法分享
- 基于TensorFlow中自定義梯度的2種方式
- tensorflow 查看梯度方式
- tensorflow求導(dǎo)和梯度計(jì)算實(shí)例
- Tensorflow的梯度異步更新示例
- 在Tensorflow中實(shí)現(xiàn)梯度下降法更新參數(shù)值
- Tensorflow實(shí)現(xiàn)部分參數(shù)梯度更新操作
- 運(yùn)用TensorFlow進(jìn)行簡(jiǎn)單實(shí)現(xiàn)線性回歸、梯度下降示例
- Tensorflow 卷積的梯度反向傳播過程
相關(guān)文章
Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例
這篇文章主要介紹了Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例,具有一定借鑒價(jià)值,需要的朋友可以了解下。2017-12-12OPENCV去除小連通區(qū)域,去除孔洞的實(shí)例講解
今天小編就為大家分享一篇OPENCV去除小連通區(qū)域,去除孔洞的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06Python numpy.power()函數(shù)使用說明
這篇文章主要介紹了Python numpy.power()函數(shù)使用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03python調(diào)用opencv實(shí)現(xiàn)貓臉檢測(cè)功能
這篇文章主要介紹了python調(diào)用opencv實(shí)現(xiàn)貓臉檢測(cè)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01Python 實(shí)現(xiàn)LeNet網(wǎng)絡(luò)模型的訓(xùn)練及預(yù)測(cè)
本文將為大家詳細(xì)講解如何使用CIFR10數(shù)據(jù)集訓(xùn)練模型以及用訓(xùn)練好的模型做預(yù)測(cè)。代碼具有一定價(jià)值,感興趣的小伙伴可以學(xué)習(xí)一下2021-11-11使用Python來編寫HTTP服務(wù)器的超級(jí)指南
這篇文章主要介紹了使用Python來編寫HTTP服務(wù)器的超級(jí)指南,同時(shí)介紹了基于Python框架的web服務(wù)器的編寫方法,譯文從理論到實(shí)現(xiàn)講得都很生動(dòng)詳細(xì),十分推薦!需要的朋友可以參考下2016-02-02