Tensor
Tensor
和NumPy的多维数组非常类似。然而,Tensor
提供GPU计算和自动求梯度等更多功能。
tensor的创建
requires_grad默认为False,不可求导
import torch
x = torch.empty(5, 3)
x = torch.rand(5, 3)
x=torch.zeros(5, 3, dtype=torch.long)
x = torch.tensor([5.5, 3])
其它函数
函数 | 功能 |
---|---|
Tensor(*sizes) | 基础构造函数 |
tensor(data,) | 类似np.array的构造函数 |
ones(*sizes) | 全1Tensor |
zeros(*sizes) | 全0Tensor |
eye(*sizes) | 对角线为1,其他为0 |
arange(s,e,step) | 从s到e,步长为step |
linspace(s,e,steps) | 从s到e,均匀切分成steps份 |
rand/randn(*sizes) | 均匀/标准分布 |
normal(mean,std)/uniform(from,to) | 正态分布/均匀分布 |
randperm(m) | 随机排列 |
这些创建方法都可以在创建的时候指定数据类型dtype和存放device(cpu/gpu)
获取Tensor
的形状:通过shape
或者size()
print(x.size())
print(x.shape)
torch.Size([5, 3])
torch.Size([5, 3])
Tensor和numpy互换
#将tensor转换成numpy
a = torch.ones(5)
b = a.numpy()
#将numpy转换成tensor
a = np.ones(5)
b = torch.from_numpy(a)
tensor 在GPU和CPU上互换
if torch.cuda.is_available():
device = torch.device("cuda") # GPU
y = torch.ones_like(x, device=device) # 直接创建一个在GPU上的Tensor
x = x.to(device) # 等价于 x=x.to("cuda")
z = x + y #z:"cuda"
z=z.to("cpu", torch.double)) # to()还可以同时更改数据类型
tensor 的自动求导
PyTorch提供的autograd包能够根据输入和前向传播过程自动构建计算图,并执行反向传播。
torch建立目标,默认requires_grad是False,可以使用requires_grad_(True)改成True,如果A的requires_grad是True,则Y=A+2的requires_grad是True。
a=torch.rand(2,3)
print (a.requires_grad) #默认False
b=a.requires_grad_(True)#改成True
print (b.requires_grad)
grad在反向传播过程中是累加的(accumulated),这意味着每一次运行反向传播,梯度都会累加之前的梯度,所以一般在反向传播之前需把梯度清零。
x.grad.data.zero_()#梯度清零
out.backward() #反向传播