tf.gradients

本文详细介绍了TensorFlow中tf.gradients函数的使用方法及参数解释,并通过实例演示了如何利用该函数进行偏导数计算,同时对比了tf.stop_gradients的不同用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tf.gradients

tf.gradients(
ys,
xs,
grad_ys=None,
name=’gradients’,
colocate_gradients_with_ops=False,
gate_gradients=False,
aggregation_method=None,
stop_gradients=None
)

功能

ys, xs 均是包含tensor的list, ys中的每个tensor和xs中的tensor相关

计算步骤:(求和可以理解为batch内的累加)

Σlen(ys)iys[i]xs[j],j[0,len(xs)1]Σilen(ys)∂ys[i]∂xs[j],∀j∈[0,len(xs)−1]

stop_gradients 用于指定偏导停止链式法则的节点。

import tensorflow as tf 

a = tf.constant([0.0])

b = a * 2

pg = tf.gradients(a+b, [a, b])

with tf.Session() as sess:
    res = sess.run(pg)
    print(res)
[array([3.], dtype=float32), array([1.], dtype=float32)]
import tensorflow as tf 

a = tf.constant([0.0])

b = a * 2

pg = tf.gradients(a+b, [a, b], stop_gradients=[a,b])

with tf.Session() as sess:
    res = sess.run(pg)
    print(res)
[array([1.], dtype=float32), array([1.], dtype=float32)]

和tf.stop_gradients区别

tf.stop_gradients 是在构建图的过程中使用,指定停止链式法则的节点

stop_gradients是在构建图之后使用

当程序运行时,碰到以上两种方式定义的stop_gradients, 均会停止链式法则,进而求得部分偏导。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值