gpt4 book ai didi

torch - requires_grad 与叶节点的关系

转载 作者:行者123 更新时间:2023-12-04 17:31:16 27 4
gpt4 key购买 nike

来自 docs :

requires_grad – Boolean indicating whether the Variable has been created by a subgraph containing any Variable, that requires it. Can be changed only on leaf Variables


  • 这里的叶子节点是什么意思?叶节点只是输入节点吗?
  • 如果它只能在叶节点上更改,那么我如何卡住层?
  • 最佳答案

  • 图的叶节点是那些不是直接从图中的其他节点计算出来的节点(即 Variables)。例如:
    import torch
    from torch.autograd import Variable

    A = Variable(torch.randn(10,10)) # this is a leaf node
    B = 2 * A # this is not a leaf node
    w = Variable(torch.randn(10,10)) # this is a leaf node
    C = A.mm(w) # this is not a leaf node

    如果一个叶子节点requires_grad ,从它计算的所有后续节点也将自动 require_grad .否则,您无法应用链式法则来计算requires_grad 的叶节点的梯度。 .这就是为什么requires_grad的原因只能为叶节点设置:对于所有其他节点,可以巧妙地推断,实际上是由用于计算这些其他变量的叶节点的设置决定的。
  • 请注意,在典型的神经网络中,所有参数都是叶节点。 它们不是从任何其他 Variables 计算出来的在网络中。因此,使用 requires_grad 卡住层很简单。这是从 PyTorch 文档中获取的示例:
    model = torchvision.models.resnet18(pretrained=True)
    for param in model.parameters():
    param.requires_grad = False

    # Replace the last fully-connected layer
    # Parameters of newly constructed modules have requires_grad=True by default
    model.fc = nn.Linear(512, 100)

    # Optimize only the classifier
    optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)

    尽管如此,你真正做的是卡住整个梯度计算(这是你应该做的,因为它避免了不必要的计算)。从技术上讲,您可以离开 requires_grad标记,并且只为您想要学习的参数子集定义优化器。
  • 关于torch - requires_grad 与叶节点的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913720/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com