TensorFlow梯度求解tf.gradients實例
更新時間:2020年02月04日 11:17:35 作者:yqtaowhu
今天小編就為大家分享一篇TensorFlow梯度求解tf.gradients實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了,直接上代碼吧!
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對a1,a2求導(dǎo)可得 [[2,1]]為w1對應(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實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python實戰(zhàn)之利用pygame實現(xiàn)貪吃蛇游戲(一)
這篇文章主要介紹了python實戰(zhàn)之利用pygame實現(xiàn)貪吃蛇游戲,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有很好的幫助喲,需要的朋友可以參考下2021-05-05
python3 tkinter實現(xiàn)添加圖片和文本
這篇文章主要為大家詳細(xì)介紹了python3 tkinter實現(xiàn)添加圖片和文本,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
python中l(wèi)ist循環(huán)語句用法實例
這篇文章主要介紹了python中l(wèi)ist循環(huán)語句用法,以實例形式詳細(xì)介紹了Python針對list的解析,包含各種常見的遍歷操作及原理分析,需要的朋友可以參考下2014-11-11

