1.Tensor的grad_fn操作
import torch
a=torch.ones(3,3)
print(a)
# requires_grad=True时会记录该张量进行过的操作
b=torch.ones(2,2,requires_grad=True)
print(b)
c=b+2
print(c)
print("查看c和b的grad_fn")
print(b.grad_fn) #b是自定义张量,grad_fn为None
print(c.grad_fn) #c是b进行过加法操作,显示为AddBackward0
d=b*b
print(d) #d是b进行过乘法操作,显示为MulBackward0
# 复杂操作
e=b*b*7 #2*2*7
print(e)
f=e.mean() #.mean()求平均值
print(f) #grad_fn为MeanBackward0
2.Tensor的自动求导
import torch
# requires_grad没有设定默认为False,此时不会追踪张量操作
# 张量中途可以追加requires_grad
x=torch.randn(3,3)
x=(x*6)/2
print(x,x.requires_grad)
x.requires_grad_(True)
print(x.requires_grad)
y=(x+x).sum()
print(y,y.requires_grad)
z=(x+x).sum()+1 #requires_grad只能记录最后一步操作
print(z,z.requires_grad) #requires_grad为加法AddBackward0
print("-------------")
# 已设置requires_grad为True的,中途也可以终止求导
print(x.requires_grad)
print((x+x).requires_grad)
with torch.no_grad(): #with torch.no_grad():可以控制某一步不求导
print((x+x).requires_grad)
print((x+x).requires_grad)
print("-------------")
# .detach()可以把自动求导的张量从求导图中抠出来获得一个新的Tensor
print(x.requires_grad)
m=x.detach() #m不必自动求导
print(m.requires_grad)
print(x.eq(m).all()) #但是m和x的数值一模一样