【问题标题】:How to use autograd.gradcheck in PyTorch?如何在 PyTorch 中使用 autograd.gradcheck?
【发布时间】:2019-12-28 20:16:18
【问题描述】:

文档不包含任何 gradcheck 的示例用例,它在哪里有用?

【问题讨论】:

    标签: pytorch autograd


    【解决方案1】:

    这里的文档中提供了一个示例用例:

    https://pytorch.org/docs/master/notes/extending.html

    您可能想检查您实施的后向方法 实际上计算函数的导数。可以通过 与使用小有限的数值近似进行比较 区别:

    from torch.autograd import gradcheck
    
    # gradcheck takes a tuple of tensors as input, check if your gradient
    # evaluated with these tensors are close enough to numerical
    # approximations and returns True if they all verify this condition.
    input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True))
    test = gradcheck(linear, input, eps=1e-6, atol=1e-4)
    print(test)
    

    正如上面的引用所暗示的,gradcheck 函数的目的是验证自定义后向函数是否与梯度的数值近似一致。主要用例是当您实现自定义后向操作时。 在极少数情况下,您应该在 PyTorch 中实现自己的后向函数。这是因为 PyTorch 的 autograd 功能负责计算绝大多数操作的梯度。

    最明显的例外是

    1. 您有一个函数不能表示为其他可微函数的有限组合(例如,如果您需要不完整的 gamma 函数,您可能需要编写自己的使用 numpy 和/或查找表)。

    2. 您希望加快一个特别复杂的表达式的计算速度,在应用链式法则后,该表达式的梯度可以大大简化。

    【讨论】:

    • gradcheck函数中的第一个参数指的是什么?线性层?如何将它与我编写的自定义函数一起使用?
    • gradcheck 的文档可以在here 找到。第一个参数是一个函数,它接受一个张量(大小和类型与input 相同)并返回一个张量或张量元组。
    猜你喜欢
    • 2020-05-18
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2017-11-22
    • 2019-06-10
    • 2018-05-10
    • 2020-01-23
    相关资源
    最近更新 更多