Reduction操作
Reduction操作的特点是它往往对一个Tensor内的元素执行归约操作,比如torch.max找极
大值、torch.cumsum计算累加,它还提供了dim参数来指定沿矩阵的哪个维度执行操作。
如:
#默认求取全局最大值
import torch
a = torch.tensor([[1,2],[3,4]])
print("全局最大值:",torch.max(a))
#指定维度dim后,返回最大值及其索引
torch.max(a,dim=0)
a = torch.tensor([[1,2],[3,4]])
print("沿着横轴计算每一列的累加:")
print(torch.cumsum(a,dim=0))
print("沿着纵轴计算每一行的累乘:")
print(torch.cumprod(a,dim=1))
#计算矩阵的均值,中值,协方差
a = torch.Tensor([[1,2],[3,4]])
a.mean(),a.median(),a.std()
#torch.unique用来找出矩阵中出现了哪些元素
a = torch.randint(0,3,(3,3))
print(a)
print(torch.unique(a))
运行结果:
PyTorch的自动微分
当将Tensor的requires grad属性设置为True时,PyTorch的torch.autograd会自动追踪
的计算轨迹。当需要计算微分的时候,只需要对最终计算结果的Tensor 调用backward方法,
所有计算节点的微分就会被保存在grad属性。
import torch
#当将Tendsor的requires_grad属性设置为Ture时,pyTorch的torch.autograd会自动追踪它的计算轨迹
x = torch.arange(9).view(3,3)
x.requires_grad
x = torch.rand(3,3,requires_grad=True)
print(x)
w = torch.ones(3,3,requires_grad=True)
y = torch.sum(torch.mm(w,x))
y
y.backward()
print(y.grad)
print(x.grad)
print(w.grad)
#Tensor.detach会将Tensor从计算图剥离出去,不再计算它的微分
x = torch.rand(3,3,requires_grad=True)
w = torch.ones(3,3,requires_grad=True)
print(x)
print(w)
yy = torch.mm(w,x)
detached_yy = yy.detach()
y = torch.mean(yy)
y.backward()
print(yy.grad)
print(detached_yy)
print(w.grad)
print(x.grad)
#with torch.no_grad(),包括的代码段不会计算微分
y = torch.sum(torch.mm(w,x))
print(y.requires_grad)
with torch.no_grad():
y = torch.sum(torch.mm(w,x))
print(y.requires_grad)
运行结果:
Tensor.detach会将Tensor从计算图剥离出去,不再计算它的微分
with troch.no_grad():包括的代码段不会计算微分。是一个上下文管理器,用来计算禁止梯度的计算,通常用来网络推理中,可减少计算内存的使用量。
Tensor的中文名是张量,本质上是一个多为矩阵。