tf.gradients()和tf.stop_gradient()

自动微分基本理论 自动微分基本理论 神经网络核心是自动微分,本文主要介绍如何使用自动微分,以及自动微分机制,帮助更好的使用自动微分进行训练。 一、背景 神经网络是由节点和节点间的相互连接组成的。网络中每层的每个节点代表一种特定的函数,对输入进行计算。每个函数都是由不同参数(权重w和偏置b)组成。神经网络训练的过程,就是不断让这些函数的参数进行学习、优化,能够更好的处理后面输入的过程。 让神经网络的判断更加准确,首先需要有衡量效果的工具,于是损失函数应运而生。如果想要神经网络的效果好,就要让损失函数尽可能的小,于是深度学习引入 阅读详情
AI摘要

本文介绍TensorFlow中的tf.gradients()和tf.stop_gradient()函数。tf.gradients()用于计算张量的梯度,支持多种参数设置;tf.stop_gradient()用于停止梯度计算,适用于多种场景。文章还提供了多个代码示例,帮助理解如何使用这两个函数。

参考 tf.stop_gradient - 云+社区 - 腾讯云

1、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,
    unconnected_gradients=tf.UnconnectedGradients.NONE
)

参数:

  • ys:  要微分的张量或张量列表。
  • xs:  用于微分的张量或列表。
  • grad_ys:可选。一个张量或张量列表,其大小与y相同,并保持y中每个y的梯度。用于对求和后加权。
  • name:  可选名称,用于将所有渐变操作分组在一起。默认为“梯度”。
  • colocate_gradients_with_ops:  如果为真,请尝试使用相应的op来合并渐变。
  • gate_gradients:  如果为真,在操作返回的渐变周围添加一个元组。这避免了一些竞争条件。
  • aggregation_method:  指定用于合并渐变项的方法。可接受的值是类AggregationMethod中定义的常量。
  • stop_gradients:  可选。一个张量或张量的列表,不需要微分。
  • unconnected_gradients:  可选。指定给定输入张量断开连接时返回的梯度值。可接受的值是在类tf中定义的常量。UnconnectedGradients,默认值为none。

返回值:

  • xs中每个x的sum(dy/dx)的列表。

可能产生的异常:

  • LookupError: if one of the operations between x and y does not have a registered gradient function.
  • ValueError: if the arguments are invalid.
  • RuntimeError: if called in Eager mode.

 ys和xs都是张量或张量列表。grad_ys是一个张量列表,包含了ys接收到的梯度。列表的长度必须与ys相同。gradient()将ops添加到图中,输出ys对xs的导数。它返回一个长度为len(xs)的张量列表,其中每个张量都是y在ys中的和(dy/dx)。grad_ys是一个与ys长度相同的张量列表,它包含ys中每个y的初始梯度。当grad_ys为0时,为y中的每个y填充一个'1'的张量,其形状为y。用户可以提供自己的初始grad_y来计算导数,使用每个y的不同初始梯度(例如,如果想对每个y中的每个值使用不同的梯度权重)。stop_gradients是一个张量或张量列表,它被认为是关于所有xs的常数。这些张量不会反向传播,就像它们已经使用stop_gradient显式断开连接一样。除此之外,这允许计算偏导数而不是全导数。

例:

a = tf.constant(0.)
b = 2 * a
g = tf.gradients(a + b, [a, b], stop_gradients=[a, b])

这里的偏导数g的值为[1.0,1.0],与全导数tf相比。梯度(a + b, [a, b]),考虑a对b的影响,取值为[3.0,1.0]。

请注意,上述内容相当于:

a = tf.stop_gradient(tf.constant(0.))
b = tf.stop_gradient(2 * a)
g = tf.gradients(a + b, [a, b])

 stop_gradients提供了一种在图已经构建好之后停止梯度的方法,而tf.stop_gradient在构建图期间停止梯度。当这两种方法结合时,反向传播在两个tf处都停止。tf.stop_gradient节点和stop_gradients中的节点,以最先遇到的节点为准。所有整数张量对于所有xs都被认为是常量,就像它们包含在stop_gradients中一样。unconnected_gradients确定如果图中每个x未连接到ys,则为xs中的每个x返回的值。默认情况下,这不是用来防止错误的。从数学上讲,这些梯度是零,可以使用“零”选项来请求。tf.UnconnectedGradients提供了以下选项和行为:

unconnected_gradients确定如果图中每个x未连接到ys,则为xs中的每个x返回的值。默认情况下,这不是用来防止错误的。从数学上讲,这些梯度是零,可以使用“零”选项来请求。UnconnectedGradients提供了以下选项和行为:

a = tf.ones([1, 2])
b = tf.ones([3, 1])
g1 = tf.gradients([b], [a], unnconnected_gradients='none')
sess.run(g1)  # [None]

g2 = tf.gradients([b], [a], unconnected_gradients='zero')
sess.run(g2)  # [array([[0., 0.]], dtype=float32)]

2、tf.stop_gradient()

停止梯度计算。当在一个图中执行时,这个op按原样输出它的输入张量。当构建ops来计算梯度时,该op会阻止将其输入的贡献考虑在内。通常情况下,梯度发生器通过递归找出对其计算有贡献的输入,将ops添加到图中,计算指定“损失”的导数。如果将这个op插入到图中,它的输入将被梯度生成器屏蔽。它们没有考虑到计算梯度。当你想用TensorFlow计算一个值,但需要假设该值是常量时,这是非常有用的。一些例子包括:

  • EM算法中m步不应该包含通过e步输出的反向传播。
  • 玻尔兹曼机的对比发散训练,当对能量函数进行微分时,训练不能通过从模型中生成样本的图进行反向传播。
  • 对抗性训练,在对抗性示例生成过程中不应该有任何支持。

参数:

  • input:  一个张量。
  • name:  操作的名称(可选)。

返回值:

  • 一个张量。具有与输入相同的类型。

例:

# 1、计算梯度
import tensorflow as tf

w1 = tf.get_variable('w1', shape=[3])
w2 = tf.get_variable('w2', shape=[3])

w3 = tf.get_variable('w3', shape=[3])
w4 = tf.get_variable('w4', shape=[3])

z1 = w1 + w2+ w3
z2 = w3 + w4

grads = tf.gradients([z1, z2], [w1, w2, w3, w4], grad_ys=[tf.convert_to_tensor([2.,2.,3.]),
                                                          tf.convert_to_tensor([3.,2.,4.])])

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(grads))

Outout:
-------------------------------------
[array([2., 2., 3.], dtype=float32), 
array([2., 2., 3.], dtype=float32), 
array([5., 4., 7.], dtype=float32), 
array([3., 2., 4.], dtype=float32)]
-------------------------------------



# 2、阻挡节点BP的梯度

import tensorflow as tf

w1 = tf.Variable(2.0)
w2 = tf.Variable(2.0)

a = tf.multiply(w1, 3.0)
a_stoped = tf.stop_gradient(a)

# b=w1*3.0*w2
b = tf.multiply(a_stoped, w2)
gradients = tf.gradients(b, xs=[w1, w2])
print(gradients)
# 可见,一个节点被 stop之后,这个节点上的梯度,就无法再向前BP了。由于w1变量的梯度只能来自a节点,所
# 以,计算梯度返回的是None。

Output:
--------------------------------------------------------------------------
[None, <tf.Tensor 'gradients/Mul_1_grad/Mul_1:0' shape=() dtype=float32>]
--------------------------------------------------------------------------

import tensorflow as tf

a = tf.Variable(1.0)
b = tf.Variable(1.0)

c = tf.add(a, b)

c_stoped = tf.stop_gradient(c)

d = tf.add(a, b)

e = tf.add(c_stoped, d)

# e = c + d = a + b + a + b

gradients = tf.gradients(e, xs=[a, b])

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(gradients))

# 虽然 c节点被stop了,但是a,b还有从d传回的梯度,所以还是可以输出梯度值的。

Output:
-----------
[1.0, 1.0]
-----------

import tensorflow as tf

w1 = tf.Variable(2.0)
w2 = tf.Variable(2.0)
a = tf.multiply(w1, 3.0)
a_stoped = tf.stop_gradient(a)

# b=w1*3.0*w2
b = tf.multiply(a_stoped, w2)

opt = tf.train.GradientDescentOptimizer(0.1)

gradients = tf.gradients(b, xs=tf.trainable_variables())

tf.summary.histogram(gradients[0].name, gradients[0])
# 这里会报错,因为gradients[0]是None
#其它地方都会运行正常,无论是梯度的计算还是变量的更新。总觉着tensorflow这么设计有点不好,
#不如改成流过去的梯度为0
train_op = opt.apply_gradients(zip(gradients, tf.trainable_variables()))

print(gradients)
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(train_op))
    print(sess.run([w1, w2]))

# 3、求高阶导数
import tensorflow as tf

with tf.device('/cpu:0'):
    a = tf.constant(1.)
    b = tf.pow(a, 2)
    grad = tf.gradients(ys=b, xs=a) # 一阶导
    print(grad[0])
    grad_2 = tf.gradients(ys=grad[0], xs=a) # 二阶导
    grad_3 = tf.gradients(ys=grad_2[0], xs=a) # 三阶导
    print(grad_3)

with tf.Session() as sess:
    print(sess.run(grad_3))

Output:
--------------------------------------------------------------------------------------
Tensor("gradients/Pow_grad/Reshape:0", shape=(), dtype=float32, device=/device:CPU:0)
[<tf.Tensor 'gradients_2/gradients_1/gradients/Pow_grad/Pow_grad/Pow_grad/Reshape:0' shape=() dtype=float32>]
[0.0]
---------------------------------------------------------------------------------------

原链接: 

tf.gradients  |  TensorFlow Core v2.7.0

https://tensorflow.google.cn/versions/r1.11/api_docs/python/tf/stop_gradient?hl=en

Tensorflow中k.gradients()和tf.stop_gradient()用法说明 主要介绍了Tensorflow中k.gradients()和tf.stop_gradient()用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 立即下载

相关推荐

集成运放内部电路组成(上)

目录 ​ 一,概述 1.1集成运放的发展 1.2集成运放特点 二,电流源电路 2.1镜像电流源电路 2.2.改进的镜像电流源 2.3微电流源 2.4比例电流源 三,差分放大电路 差动放大电路的静态分析 差动放大电路差模信号的动态分析 双入单出 总结: 四,复合管电路 五,集成运放的输出 一,概述 1.1集成运放的发展 随着半导体技术的发展,采用半导体制造工艺将电阻、三极管等元器件及电路的连线全部制造到一块半导体基片上,其本...

梦灵-影的博客 1万+

tf.stop_gradient

详细可以参见链接:关于tf.stop_gradient的使用及理解 关于stop_gradient 有时候我们其实不希望某些参数进行反向传播,这时候可以用这个函数,引入stop_gradient来对从loss到target net的反传进行截断。 目的主要是在计算loss的时候,只对一部分进行权重更新 ...

2242

考试遇到 Assistant API 考点时,该掌握哪些要点?

【摘要】聚焦阿里云大模型 ACP 认证中智能体 Assistant API 考点,我结合自学认证成功经验,分享复习攻略。先解析 assistants、threads 等五个核心组件作用与关系,点明各组件支持及不支持的方法,最后给出计算 Python 代码调用大模型次数的思路,助力考生攻克考点、顺利拿证 。

davidkorhenn的博客 499

tensorflow—tf.gradients()简单实用教程

声明: 参考官方文档 参考tensorflow学习笔记(三十) 关于神经网络中的梯度计算,推荐吴恩达的deeplearning公开课 tf.gradients() 在tensorflow中,tf.gradients()的参数如下: tf.gradients(ys, xs, grad_ys=None, name='gradients...

hustqb的博客 6万+

AIDL HAL服务从零到一:构建现代Android硬件抽象层

本文详细介绍了从零开始构建现代Android AIDL HAL服务的完整流程。通过定义接口、实现服务逻辑、配置构建与VINTF清单,并最终集成到系统镜像,开发者可以掌握利用AIDL替代传统HIDL来开发硬件抽象层的核心方法。文章重点解析了AIDL HAL的创建流程,并对比了其与HIDL在语法、工具链和集成方式上的优势,帮助开发者高效构建稳定的硬件接口。

weixin_29174141的博客 150

保姆级教程:用Fiddler+夜神模拟器搞定抖音App抓包(附SSL Pinning绕过实战)

本文提供了一套完整的移动端抓包解决方案,详细介绍了如何使用Fiddler和夜神模拟器进行抖音App抓包,并重点讲解了SSL Pinning绕过技术。通过Xposed框架和JustTrustMe模块的组合,实现高效抓包,适用于产品分析、竞品研究和安全测试等场景。

weixin_30855099的博客 429

Tensorflow中k.gradients()和tf.stop_gradient()的深入理解

上周在实验室开荒某个代码,看到中间这么一段,对Tensorflow中的stop_gradient()还不熟悉,特此周末进行重新并总结。 y = xx + K.stop_gradient(rounded - xx) 这代码最终调用位置在tensoflow.python.ops.gen_array_ops.stop_gradient(input, name=None),关于这段代码...

码农的科研笔记 1万+

【无标题】

可以看到这是一个带过滤的rce,并且还需要绕过空格,通过·查询资料得到了${IFS},$IFS$9,<,$IFS。然后f,l,a,g都被过滤了,可以用中括号[]来进行正则匹配,把GET传的参数改为?cmd=uniq /[e-h][k-n][^-b][e-h],就得到了flag。cmd={%0A"cmd":"/bin/cat /home/rceservice/flag"%0A}可以看到l被过滤了ls用不了了可以用dir用GET传参cmd=dir /,POST传参shell=system。

2501_94507425的博客 315

TensorFlow学习3:tf.gradients和tf.stop_gradient()

本文转载自http://blog.csdn.net/u012436149/article/details/53905797gradienttensorflow中有一个计算梯度的函数tf.gradients(ys, xs),要注意的是,xs中的x必须要与ys相关,不相关的话,会报错。 代码中定义了两个变量w1, w2, 但res只与w1相关#wrong import tensorflow as tf...

攻城狮的自我修养 973

【通信协议】I2C总线(一主多从)

I2C总线(一主多从)之软件模拟代码详解

m0_75090944的博客 9868

SQLSTATE58030

在优化一条SQL的时候遇到了执行错误 gtlions =# select t1.telnumber,t2.ua,t2.url,t1.apply_name,t2.apply_name from tb1 t1 gtlions -# left outer join tb2 t2 on t1.sid = t2.ipsid gtlions-# where t1.sum_date=20141128 a

Gtlions Tracker 3664

冻结变量方法(tensorflow freeze variable)

若tensorflow构造的模型中部分变量需要冻结, 有以下三种方法: 1.名词解释 冻结变量,指的是在训练模型时,对某些可训练变量不更新,即仅参与前向loss计算,不参与后向传播,一般用于模型的finetuning等场景。例如:我们在其他数据上训练了一个resnet152模型,然后希望在目前数据上做finetuning,一般来讲,网络的前几层卷积是用来提取底层图像特征的,因此可以对前3个卷积...

hellocsz的博客 1675

DDR5 的 PI: DIMM 上 PMIC,正在制造一批“新型 EMI 问题”

DDR5 的 PI,不再只是“供电设计”,而是一次“噪声管理设计”。电压稳定本地调节高频噪声EMI 风险系统不确定性DDR5 真正难的地方,不是跑起来,而是——在最差条件下,它还能不能一直跑。而 DIMM 上那颗 PMIC,正是你绕不开的关键角色。

weixin_43199439的博客 189

tf.gradients、tf.compute_gradients和tf.stop_gradient

import tensorflow as tf w = tf.Variable([2., 5.]) # u = tf.Variable([7., 9.]) y = 2 * w x = 2 * y z = 2 * x stop_y = tf.stop_gradient(y) stop_x = 2 * stop_y grad1 = tf.gradients(y, w) grad2 = tf.grad...

Seventeen0084的博客 1520

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Tensorflow:tf.gradient()用法以及参数stop_gradient理解

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

Invokar的博客 1万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

tensorflow学习笔记(三十):tf.gradients 与 tf.stop_gradient() 与 高阶导数

gradienttensorflow中有一个计算梯度的函数tf.gradients(ys, xs),要注意的是,xs中的x必须要与ys相关,不相关的话,会报错。 代码中定义了两个变量w1, w2, 但res只与w1相关#wrong import tensorflow as tfw1 = tf.Variable([[1,2]]) w2 = tf.Variable([[3,4]])res = tf.m

Keith 5万+

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Tensorflow tf.gradients 详解

tf.gradients gradients( ys, xs, grad_ys=None, name=‘gradients’, colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None ) 在 xs 中构造了 ys 的 w.r.t. x 和的符号偏导数. ys 和 xs 是一个张量或一个张量的列...

ip5108的博客 5282

opt.compute_gradients() 与 tf.gradients 与 tf.stop_gradient()

def gradients(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None) """Constructs symbolic partial derivatives of

YiqiangXu的博客 4986

tensorflow 中的tf.gradients 与 tf.stop_gradient() 函数

转载网址:http://blog.csdn.net/u012436149/article/details/53905797 gradient tensorflow中有一个计算梯度的函数tf.gradients(ys, xs),要注意的是,xs中的x必须要与ys相关,不相关的话,会报错。 代码中定义了两个变量w1, w2, 但res只与w1相关 #wrong import tenso

wuguangbin1230的博客 1万+

tensorflow的tf.gradients和tf.stop_gradients

1.tf.gradients的功能介绍 首先看下tf.gradients的功能,字面意思就很容易看出,tf.gradients用来对变量求梯度,我们给出一个简单的例子: import tensorflow as tf sess = tf.Session() a = tf.Variable(0.,name="a") b = tf.Variable(0.,name="b") c=5*a+b print(sess.run(tf.gradients(c, [a, b]))) print(sess.run(tf

fangfanglovezhou的博客 625

tensorflow with求导_tensorflow学习笔记(三十):tf.gradients与tf.stop_gradient与高阶导数...

gradienttensorflow中有一个计算梯度的函数tf.gradients(ys, xs),要注意的是,xs中的x必须要与ys相关,不相关的话,会报错。代码中定义了两个变量w1, w2, 但res只与w1相关#wrongimport tensorflow as tfw1 = tf.Variable([[1,2]])w2 = tf.Variable([[3,4]])res = tf.matm...

weixin_39962199的博客 335

Tensorflow中的各种梯度处理gradient

最近其实一直想自己手动创建op,这样的话好像得懂tensorflow自定义api/op的规则,设计前向与反向,注册命名,注意端口以及文件组织,最后可能还要需要重新编译才能使用。这一部分其实记得tensorflow官网上(可能是老版)有过介绍,但是当时没有仔细研究,也可能写的不够清晰,打算之后再专门写一篇博客介绍。本文主要介绍不自定义op的前提下,实现最大自由度的梯度计算与处理。 一、tf.gr...

edward_zcl的博客 8104

tf.gradients

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

ustc_imcl_fj的博客 1278

深入理解Tensorflow中的梯度计算算子-tf.gradients()

转载:https://blog.csdn.net/hustqb/article/details/80260002声明:参考官方文档参考tensorflow学习笔记(三十)关于神经网络中的梯度计算,推荐吴恩达的deeplearning公开课tf.gradients()在tensorflow中,tf.gradients()的参数如下:tf.gradients(ys, xs, ...

David's Tweet 9366

tensorflow中gradients基本用法

import tensorflow as tf """ 在反向传播过程中,神经网络需要对 loss 对应的学习参数求偏导(也叫梯度), 该值用来乘以学习率然后更新学习参数使用的。 它是通过 tf.gradients 函数来实现的 """ weight = tf.Variable([[1, 2]]) y = tf.matmul(weight, [[9], [10]]) """ 第一个参数:求导公式...

qq_42413820的博客 2265
上一篇: tf.variable_scope()
下一篇: tf.reduce_mean
Wanderer001
博客等级 码龄10年 1835粉丝 1869原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wanderer001

ROIAlign原理

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值