zoukankan      html  css  js  c++  java
  • AUTOGRAD: 自动分化(pytorch官网60分钟闪电战第二节)

    import torch
    

    一、Tensor

    该节使用了跟踪张量,当对x进行设置requires_grad=True,那么后续对x的操作都要转换为含x的公式,这样就体现了跟踪这一含义。

    # 创建一个张量并设置requires_grad=True为跟踪张量
    x = torch.ones(2, 2, requires_grad=True)
    print(x)
    # 用户自己创建的没有grad_fn
    print(x.grad_fn)
    # 进行张量运算
    y = x + 2
    # y是由于操作而创建的,因此具有grad_fn
    print(y)
    print(y.grad_fn)
    # 进行更多操作 y
    z = y * y * 3
    out = z.mean()
    
    print(z, out)
    
    # requires_grad 就地更改现有Tensor的标志。输入标志默认为False
    a = torch.ones(2, 2)
    print(a)
    print(a.requires_grad)
    a.requires_grad_(True)
    print(a.requires_grad)
    # 对应位相承,和torch.mul相同,不是矩阵相乘,矩阵相乘是torch.mm
    b = a * a
    print(b)
    b = b.sum()
    print(b)
    print(b.grad_fn)
    

    二、Gradients

    # 1.创建一个张量并设置requires_grad=True为跟踪张量
    x = torch.ones(2, 2, requires_grad=True)
    y = x + 2
    z = y * y * 3
    out = z.mean()
    # print(out)
    # 完成计算后,可以调用.backward()并自动计算所有梯度
    out.backward()
    # 该张量的梯度将累加到.grad属性中,结果应该是z=3(x+2)^2中的x求偏导,最后除以张量大小4,具体过程可参考pytorch官网介绍
    # print(x.grad)
    
    # 2.向量雅可比积
    x = torch.randn(3, requires_grad=True)
    print(x)
    print(x.mean())
    y = x * 2
    # 其实就是先对y中每一项取平方,之后累加,最后取根号
    # y.data.norm() = torch.sqrt(torch.sum(torch.pow(y,2)))
    i = 0
    while y.data.norm() < 1000:
        y = y * 2
        i += 1
    
    print(i)
    print(y)
    
    v = torch.tensor([2, 1, 1], dtype=torch.float)
    # 如果只想要向量-雅可比积,只需将向量传递给 backward作为参数:
    y.backward(v)
    print(x.grad)
    
    print(x.requires_grad)
    print((x ** 2).requires_grad)
    with torch.no_grad():
        print((x ** 2).requires_grad)
    
    print(x.requires_grad)
    # 要停止张量跟踪历史记录,可以调用.detach()将其从计算历史记录中分离出来,并防止跟踪将来的计算。
    y = x.detach()
    print(y.requires_grad)
    print(x.eq(y).all())
    
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/ycycn/p/13788359.html
Copyright © 2011-2022 走看看