PyTorch 之Varible

构建Variable. 要谊意得传入一个参数 requires_grad=True ,这个参数表 是否对这个变量求梯度,默认的 Fa!se ,也就是不对这个变量求梯度,这里我们希望得到这些变量的梯度,所以需要传入这个参数从的代码中,我们看到了一行 y.backward() ,这 行代码就是所谓的自动求导,

import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt

x=Variable(torch.Tensor([1]),requires_grad=True)#默认为false
w=Variable(torch.Tensor([2]),requires_grad=True)
b=Variable(torch.Tensor([3]),requires_grad=True)

y=w*x+b
y.backward()#自动求导
print(x.grad)#2
print(w.grad)#1
print(b.grad)#1

猜你喜欢

转载自blog.csdn.net/weixin_42528089/article/details/84871044