python grad_torch.autograd.grad()函数用法示例
目录
一、函数解释
如果输入x,输出是y,则求y关于x的导数(梯度):
def grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False,
only_inputs=True, allow_unused=False):
r"""Computes and returns the sum of gradients of outputs w.r.t. the inputs.
``grad_outputs`` should be a sequence of length matching ``output``
containing the pre-computed gradients w.r.t. each of the outputs. If an
output doesn't require_grad, then the gradient can be ``None``).
If ``only_inputs`` is ``True``, the function will only return a list of gradients
w.r.t the specified inputs. If it's ``False``, then gradient w.r.t. all remaining
leaves will still be computed, and will be accumulated into their ``.grad``
attribute.
Arguments:
outputs (sequence of Tensor): outputs of the differentiated function.
inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
returned (and not accumulated into ``.grad``).
grad_outputs (sequence of Tensor): Gradients w.r.t. each output.
None values can be specified for scalar Tensors or ones that don't require
grad. If a None value would be acceptable for all grad_tensors, then this
argument is optional. Default: None.
retain_graph (bool, optional): If ``False``, the graph used to compute the grad
will be freed. Note that in nearly all cases setting this option to ``True``
is not needed and often can be worked around in a much more efficient
way. Defaults to the value of ``create_graph``.
create_graph (bool, optional): If ``True``, graph of the derivative will
be constructed, allowing to compute higher order derivative products.
Default: ``False``.
allow_unused (bool, optional): If ``False``, specifying inputs that were not
used when computing outputs (and therefore their grad is always zero)
is an error. Defaults to ``False``.
"""
if not only_inputs:
warnings.warn("only_inputs argument is deprecated and is ignored now "
"(defaults to True). To accumulate gradient for other "
"parts of the graph, please use torch.autograd.backward.")
outputs = (outputs,) if isinstance(outputs, torch.Tensor) else tuple(outputs)
inputs = (inputs,) if isinstance(inputs, torch.Tensor) else tuple(inputs)
if grad_outputs is None:
grad_outputs = [None] * len(outputs)
elif isinstance(grad_outputs, torch.Tensor):
grad_outputs = [grad_outputs]
else:
grad_outputs = list(grad_outputs)
grad_outputs = _make_grads(outputs, grad_outputs)
if retain_graph is None:
retain_graph = create_graph
return Variable._execution_engine.run_backward(
outputs, grad_outputs, retain_graph, create_graph,
inputs, allow_unused)
二、代码范例(y=x^2)
import torch
x = torch.randn(3, 4).requires_grad_(True)
for i in range(3):
for j in range(4):
x[i][j] = i + j
y = x ** 2
print(x)
print(y)
weight = torch.ones(y.size())
print(weight)
dydx = torch.autograd.grad(outputs=y,
inputs=x,
grad_outputs=weight,
retain_graph=True,
create_graph=True,
only_inputs=True)
"""(x**2)' = 2*x """
print(dydx[0])
d2ydx2 = torch.autograd.grad(outputs=dydx[0],
inputs=x,
grad_outputs=weight,
retain_graph=True,
create_graph=True,
only_inputs=True)
print(d2ydx2[0])
x是:
tensor([[0., 1., 2., 3.],
[1., 2., 3., 4.],
[2., 3., 4., 5.]], grad_fn=)
y = x的平方:
tensor([[ 0., 1., 4., 9.],
[ 1., 4., 9., 16.],
[ 4., 9., 16., 25.]], grad_fn=)
weight:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
dydx就是
(一阶导数),得到结果还需要乘以weight:
tensor([[ 0., 2., 4., 6.],
[ 2., 4., 6., 8.],
[ 4., 6., 8., 10.]], grad_fn=)
d2ydx2就是
(二阶导数),得到结果还需要乘以weight:
tensor([[2., 2., 2., 2.],
[2., 2., 2., 2.],
[2., 2., 2., 2.]], grad_fn=)
是不是很简单呢~
python grad_torch.autograd.grad()函数用法示例相关推荐
- python 匿名函数示例_扣丁学堂Python3开发之匿名函数用法示例详解
扣丁学堂Python3开发之匿名函数用法示例详解 2018-07-26 14:01:11 1324浏览 今天扣丁学堂Python培训给大家分享关于Python3匿名函数用法,结合实例形式分析了Pyth ...
- python中match的六种用法,python 正则函数match()和search()用法示例
这篇文章主要为大家详细介绍了python 正则函数match()和search()用法示例,具有一定的参考价值,可以用来参考一下. 对python正则表达式函数match()和search()的区别详 ...
- php指定长度 分割整形,php指定长度分割字符串str_split函数用法示例
本文实例讲述了php指定长度分割字符串str_split函数用法.分享给大家供大家参考,具体如下: 示例1:$str = 'abcdefgh'; $arr = str_split($str,2); 运 ...
- python中index函数_详解python中的index函数用法
1.函数的创建 def fun(): #定义 print('hellow') #函数的执行代码 retrun 1 #返回值 fun() #执行函数 2.函数的参数 普通参数 :要按照顺序输入参数 de ...
- python中的lambda函数用法--无需定义函数名的函数或子程序,避免代码充斥着大量单行函数
匿名函数lambda:是指一类无需定义标识符(函数名)的函数或子程序. lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值. 要点: lambda 函数不能包含命令 包含 ...
- php解escape,PHP下escape解码函数用法示例
这篇文章主要为大家详细介绍了PHP下escape解码函数用法示例,具有一定的参考价值,可以用来参考一下. 感兴趣的小伙伴,下面一起跟随512笔记的小编小韵来看看吧!GB2312编码: 代码如下: fu ...
- python中index方法详解_详解python中的index函数用法
1.函数的创建 def fun(): #定义 print('hellow') #函数的执行代码 retrun 1 #返回值 fun() #执行函数 2.函数的参数 普通参数 :要按照顺序输入参数 de ...
- mysql中vlookup函数_vlookup函数用法示例,如何使用vlookup函数
vlookup函数用法示例,如何使用vlookup函数 优亿在线 26 2020-10-30 在excel中提及数据查看,很多人最先想起的便是vlookup函数,由于很多人第一个触碰到的函数便是vlo ...
- php中fread用法,php fread()函数用法示例
这篇文章主要为大家详细介绍了php fread()函数用法示例,具有一定的参考价值,可以用来参考一下. 对php中fread()函数使用技巧感兴趣的小伙伴,下面一起跟随512笔记的小编两巴掌来看看吧! ...
最新文章
- 拼多多面试真题:如何用 Redis 统计独立用户访问量!
- NPM:Cannot read property 'pause' of undefined
- tomcat linux dump,Linux下Tomcat常用命令与配置
- 简单点名小程序(伪)----android开发
- 使用Dockerfile定制镜像来部署Tomcat项目
- pyqt5信号与槽连接的生命周期与对象引用的生命周期
- MATLAB画频率响应曲线(幅频特性和相频特性)并将横坐标转换为赫兹hz单位
- C语言大数运算-大数运算库篇
- (原創) 如何一個字元一個字元的印出字串? (C/C++) (C)
- Matlab(将2维图片显示成3维图形)
- 最近在读的一些文章-2019.04
- 【DM】教你用JDBC连接达梦数据库并进行增删改查
- CSS中的overflow,
- LoopyCuts编译运行方法
- python 进阶 【封装】 适合小白入门
- Tmp112数字温度传感器
- MySQL基础教程系列-约束(三)唯一约束
- 引文分析软件histcite简介(中科大 罗昭锋)
- 给 iOS 装上旧版 APP,十年前的 iPad mini 重获新生!
- 5款相见恨晚的在线设计工具,原型海报流程图轻松搞定