【问题标题】:How do you use next_functions[0][0] on grad_fn correctly in pytorch?如何在 pytorch 中正确使用 grad_fn 上的 next_functions[0][0]?
【发布时间】:2020-09-15 18:45:56
【问题描述】:

我在官方的 pytorch 教程中得到了这个 nn 结构:

输入 -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> 视图 -> 线性 -> relu -> 线性 -> relu -> 线性 -> MSELoss -> 损失

然后是如何使用变量中的内置 .grad_fn 向后跟踪 grad 的示例。

# Eg: 
print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU

所以我认为我可以通过粘贴 next_function[0][0] 9 次来到达 Conv2d 的 grad 对象,因为给出的示例但我得到了错误元组超出索引。那么如何正确索引这些反向传播对象呢?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    PyTorch CNN tutorial 中运行教程中的以下内容后:

    output = net(input)
    target = torch.randn(10)  # a dummy target, for example
    target = target.view(1, -1)  # make it the same shape as output
    criterion = nn.MSELoss()
    
    loss = criterion(output, target)
    print(loss)
    

    以下代码 sn -p 将打印完整的图表:

    def print_graph(g, level=0):
        if g == None: return
        print('*'*level*4, g)
        for subg in g.next_functions:
            print_graph(subg[0], level+1)
    
    print_graph(loss.grad_fn, 0)
    

    【讨论】:

      【解决方案2】:

      尝试运行

      print(loss.grad_fn.next_functions[0][0].next_functions)

      你会看到这给出了一个包含三个元素的数组。它实际上是您要选择的 [1][0] 元素,否则您将获得累积的 grad 并且您不能再进一步了。当您深入挖掘时,您会发现您可以一直通过网络。例如,尝试运行:

      print(loss.grad_fn.next_functions[0][0].next_functions[1][0].next_functions[0][0].next_functions[1][0].next_functions[0][0].next_functions[1][0].next_functions[0][0].next_functions[0][0].next_functions[0][0].next_functions)

      先运行 .next_functions 而不用索引,然后看看你需要选择哪个元素才能到达 nn 的下一层。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 2020-08-31
        • 2017-03-10
        • 2012-02-17
        • 2020-05-16
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        相关资源
        最近更新 更多