python求导函数_pytorch基础五(定义自动求导函数)

本人学习pytorch主要参考官方文档和 莫烦Python中的pytorch视频教程。

后文主要是对pytorch官网的文档的总结。

代码来自pytorch官网

import torch

# 通过继承torch.autograd.Function类,并实现forward 和 backward函数

class MyReLU(torch.autograd.Function):

@staticmethod

def forward(ctx, input):

"""

在forward函数中,接收包含输入的Tensor并返回包含输出的Tensor。

ctx是环境变量,用于提供反向传播是需要的信息。可通过ctx.save_for_backward方法缓存数据。

"""

ctx.save_for_backward(input)

return input.clamp(min=0)

@staticmethod

def backward(ctx, grad_output):

"""

在backward函数中,接收包含了损失梯度的Tensor,

我们需要根据输入计算损失的梯度。

"""

input, = ctx.saved_tensors

grad_input = grad_output.clone()

grad_input[input < 0] = 0

return grad_input

dtype = torch.float

device = torch.device("cpu")

N, D_in, H, D_out = 64, 1000, 100, 10

x = torch.randn(N, D_in, device=device, dtype=dtype)

y = torch.randn(N, D_out, device=device, dtype=dtype)

w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)

w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)

learning_rate = 1e-6

for t in range(500):

relu = MyReLU.apply

y_pred = relu(x.mm(w1)).mm(w2)

loss = (y_pred - y).pow(2).sum()

print(t, loss.item())

loss.backward()

with torch.no_grad():

w1 -= learning_rate * w1.grad

w2 -= learning_rate * w2.grad

w1.grad.zero_()

w2.grad.zero_()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值