Learning Pytorch with examples

本文介绍如何通过继承torch.autograd.Function并实现前向和后向传播来创建自定义的自动梯度函数。文章提供了一个具体的例子,演示了如何使用自定义的ReLU激活函数进行神经网络训练。

This blog is trying so solve problems met in Learning Pytorch with examples

torch.autograd.Function

# -*- coding: utf-8 -*-
import torch


class MyReLU(torch.autograd.Function):
    """
    We can implement our own custom autograd Functions by subclassing
    torch.autograd.Function and implementing the forward and backward passes
    which operate on Tensors.
    """

    @staticmethod
    def forward(ctx, input):
        """
        In the forward pass we receive a Tensor containing the input and return
        a Tensor containing the output. ctx is a context object that can be used
        to stash information for backward computation. You can cache arbitrary
        objects for use in the backward pass using the ctx.save_for_backward method.
        """
        ctx.save_for_backward(input)
        return input.clamp(min=0)

    @staticmethod
    def backward(ctx, grad_output):
        """
        In the backward pass we receive a Tensor containing the gradient of the loss
        with respect to the output, and we need to compute the gradient of the loss
        with respect to the input.
        """
        input, = ctx.saved_tensors
        grad_input = grad_output.clone()
        grad_input[input < 0] = 0
        return grad_input


dtype = torch.float
device = torch.device("cpu")
# dtype = torch.device("cuda:0") # Uncomment this to run on GPU

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random Tensors to hold input and outputs.
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

# Create random Tensors for weights.
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):
    # To apply our Function, we use Function.apply method. We alias this as 'relu'.
    relu = MyReLU.apply

    # Forward pass: compute predicted y using operations; we compute
    # ReLU using our custom autograd operation.
    y_pred = relu(x.mm(w1)).mm(w2)

    # Compute and print loss
    loss = (y_pred - y).pow(2).sum()
    print(t, loss.item())

    # Use autograd to compute the backward pass.
    loss.backward()

    # Update weights using gradient descent
    with torch.no_grad():
        w1 -= learning_rate * w1.grad
        w2 -= learning_rate * w2.grad

        # Manually zero the gradients after updating weights
        w1.grad.zero_()
        w2.grad.zero_()

Excellent Illustration on This Topic

PyTorch 是一种开源的深度学习框架,由 Facebook 推出,以其动态计算图(Dynamic Computational Graph)的设计和易于使用的 API 而闻名。它非常适合研究实验以及快速原型设计。 **开始学习 PyTorch 的步骤:** 1. **安装**:首先,确保你已经安装了 Python 和 pip,然后可以通过 pip 安装 torch 和 torchvision 库,这是 PyTorch 的核心组件。例如: ```bash pip install torch torchvision ``` 2. **基本概念**: - **张量(Tensor)**:PyTorch 中的核心数据结构,类似于 NumPy 的数组,但支持GPU加速。 - **自动梯度(Autograd)**:PyTorch 自动跟踪计算图,使得反向传播求导变得简单。 - **nn.Module**:定义神经网络的基本模块,包含前向传播的方法 `forward()`。 3. **入门教程**: - 官方文档:https://pytorch.org/docs/stable/getting_started.html 是非常好的起点,有详细的教程、示例和API文档。 - Codecademy 或 Coursera 上的课程,如 "Practical Deep Learning with PyTorch",提供了实践项目。 4. **实践项目**: - 利用 MNIST 数据集训练一个简单的线性分类器或卷积神经网络(CNN)。 - 使用预训练模型如 ResNet 进行图像分类或物体检测。 - 实现 GANs 或变分自编码器等更复杂的深度学习模型。 5. **社区资源**: - GitHub 上的 PyTorch 示例项目(https://github.com/pytorch/examples) - Stack Overflow 和 PyTorch 社区论坛(https://discuss.pytorch.org/)可以帮助解答问题。 6. **深入学习**: - 阅读论文和书籍,如《动手学深度学习》(Deep Learning with PyTorch) 和《PyTorch官方指南》(Learning PyTorch with Examples)。 **相关问题--:** 1. PyTorch和NumPy的主要区别是什么? 2. 如何在PyTorch中创建并操作张量? 3. 哪些情况下你会选择静态计算图框架(如TensorFlow)而不是PyTorch? 4. 如何使用PyTorch进行GPU加速?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值