Tensorflow中k.gradients()和tf.stop_gradient()用法说明

 更新时间:2020年06月10日 09:47:25   作者:书上猴爵  
这篇文章主要介绍了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),关于这段代码为什么这样写的意义在文末给出。

【stop_gradient()意义】

用stop_gradient生成损失函数w.r.t.的梯度。

【tf.gradients()理解】

tf中我们只需要设计我们自己的函数,tf提供提供强大的自动计算函数梯度方法,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
)

gradients() adds ops to the graph to output the derivatives of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the sum(dy/dx) for y in ys.

1、tf.gradients()实现ys对xs的求导

2、ys和xs可以是Tensor或者list包含的Tensor

3、求导返回值是一个list,list的长度等于len(xs)

eg.假设返回值是[grad1, grad2, grad3],ys=[y1, y2],xs=[x1, x2, x3]。则计算过程为:

import numpy as np
import tensorflow as tf
 
#构造数据集
x_pure = np.random.randint(-10, 100, 32)
x_train = x_pure + np.random.randn(32) / 32
y_train = 3 * x_pure + 2 + np.random.randn(32) / 32
 
x_input = tf.placeholder(tf.float32, name='x_input')
y_input = tf.placeholder(tf.float32, name='y_input')
w = tf.Variable(2.0, name='weight')
b = tf.Variable(1.0, name='biases')
y = tf.add(tf.multiply(x_input, w), b)
 
loss_op = tf.reduce_sum(tf.pow(y_input - y, 2)) / (2 * 32)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss_op)
gradients_node = tf.gradients(loss_op, w)
 
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
 
for i in range(20):
 _, gradients, loss = sess.run([train_op, gradients_node, loss_op], feed_dict={x_input: x_train[i], y_input: y_train[i]})
 print("epoch: {} \t loss: {} \t gradients: {}".format(i, loss, gradients))
sess.close()

自定义梯度和更新函数

import numpy as np
import tensorflow as tf
 
#构造数据集
x_pure = np.random.randint(-10, 100, 32)
x_train = x_pure + np.random.randn(32) / 32
y_train = 3 * x_pure + 2 + np.random.randn(32) / 32
 
x_input = tf.placeholder(tf.float32, name='x_input')
y_input = tf.placeholder(tf.float32, name='y_input')
w = tf.Variable(2.0, name='weight')
b = tf.Variable(1.0, name='biases')
y = tf.add(tf.multiply(x_input, w), b)
 
loss_op = tf.reduce_sum(tf.pow(y_input - y, 2)) / (2 * 32)
# train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss_op)
 
#自定义权重更新
grad_w, grad_b = tf.gradients(loss_op, [w, b])
new_w = w.assign(w - 0.01 * grad_w)
new_b = b.assign(b - 0.01 * grad_b)
 
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
 
for i in range(20):
 _, gradients, loss = sess.run([new_w, new_b, loss_op], feed_dict={x_input: x_train[i], y_input: y_train[i]})
 print("epoch: {} \t loss: {} \t gradients: {}".format(i, loss, gradients))
sess.close()

【tf.stop_gradient()理解】

在tf.gradients()参数中存在stop_gradients,这是一个List,list中的元素是tensorflow graph中的op,一旦进入这个list,将不会被计算梯度,更重要的是,在该op之后的BP计算都不会运行。

import numpy as np
import tensorflow as tf
 
a = tf.constant(0.)
b = 2 * a
c = a + b
g = tf.gradients(c, [a, b])
 
with tf.Session() as sess:
 tf.global_variables_initializer().run()
 print(sess.run(g))
 
#输出[3.0, 1.0]

在用一个stop_gradient()的例子

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)
#输出[None, <tf.Tensor 'gradients/Mul_1_grad/Reshape_1:0' shape=() dtype=float32>]
 
#实验二
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)
gradients = tf.gradients(e, xs=[a, b])
with tf.Session() as sess:
 tf.global_variables_initializer().run()
 print(sess.run(gradients))
 
#因为梯度从另外地方传回,所以输出 [1.0, 1.0]

【答案】

开始提出的问题,为什么存在那段代码:

t = g(x)

y = t + tf.stop_gradient(f(x) - t)

这里,我们本来的前向传递函数是XX,但是想要在反向时传递的函数是g(x),因为在前向过程中,tf.stop_gradient()不起作用,因此+t和-t抵消掉了,只剩下f(x)前向传递;而在反向过程中,因为tf.stop_gradient()的作用,使得f(x)-t的梯度变为了0,从而只剩下g(x)在反向传递。

以上这篇Tensorflow中k.gradients()和tf.stop_gradient()用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Linux上Miniconda的安装的实现步骤

    Linux上Miniconda的安装的实现步骤

    Miniconda是一个轻量级、免费且开源的跨平台软件包管理系统,本文主要介绍了Linux上Miniconda的安装的实现步骤,具有一定的参考价值,感兴趣的可以了解一下
    2024-03-03
  • 如何通过python的fabric包完成代码上传部署

    如何通过python的fabric包完成代码上传部署

    这篇文章主要介绍了如何通过python的fabric包完成代码上传部署,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • Jupyter notebook中如何添加Pytorch运行环境

    Jupyter notebook中如何添加Pytorch运行环境

    这篇文章主要介绍了Jupyter notebook中如何添加Pytorch运行环境,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • pandas中read_csv、rolling、expanding用法详解

    pandas中read_csv、rolling、expanding用法详解

    这篇文章主要介绍了pandas中read_csv、rolling、expanding用法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python最基本的数据类型以及对元组的介绍

    Python最基本的数据类型以及对元组的介绍

    这篇文章主要介绍了Python最基本的数据类型以及对元组的介绍,来自于IBM官方网站技术文档,需要的朋友可以参考下
    2015-04-04
  • Python Requests库及用法详解

    Python Requests库及用法详解

    Requests库作为Python中最受欢迎的HTTP库之一,为开发人员提供了简单而强大的方式来发送HTTP请求和处理响应,本文将带领您深入探索Python Requests库的世界,我们将从基础知识开始,逐步深入,覆盖各种高级用法和技巧,感兴趣的朋友一起看看吧
    2024-06-06
  • Python3中对json格式数据的分析处理

    Python3中对json格式数据的分析处理

    这篇文章主要介绍了Python3中对json格式数据的分析处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • 基于PyQt5实现的Windows定时关机工具

    基于PyQt5实现的Windows定时关机工具

    在日常使用电脑的过程中,我们经常会遇到需要定时关机的场景,虽然 Windows 自带 shutdown 命令可以定时关机,但操作方式较为繁琐,缺乏可视化界面,因此,本篇文章将带大家实现一个基于 PyQt5 的 Windows 定时关机工具,需要的朋友可以参考下
    2025-04-04
  • Tesserocr库的正确安装方式

    Tesserocr库的正确安装方式

    今天小编就为大家分享一篇关于Tesserocr库的正确安装方式,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10
  • 使用python进行量化交易的完整指南

    使用python进行量化交易的完整指南

    量化交易,作为现代金融市场中的一种先进交易方式,通过运用数学模型、统计方法和计算机算法来指导交易决策,旨在提高交易效率和决策的准确性,本文将详细介绍如何使用Python进行量化交易,包括策略开发、数据处理、回测、风险管理和实盘交易等关键步骤
    2024-09-09

最新评论