Pytorch for former Torch users - Tensors
Tensors
Pytorch 中的 Tensor 和 Torch 中的 Tensor 有着几乎相同的用法
创建一个 (5*7) 大小的未初始化的tensor
import torch
a = torch.empty(5, 7, dtype=torch.floar)
初始化一个从标准正态分布随机获得的双精度浮点数的tensor
b = torch.randn(5, 7, dtype=torch.double)
print(b.size())
# torch.Size([5, 7])
Note: torch.Size 实际上是一个元组(tuple)
Inplace / Out-of-place
tensor上所有就地操作都会在加有后缀 _
例如,add是易地版本, add_是就地版本
有些操作,例如narrow没有就地版本,而像fill_的操作没有易地版本
Zero Indexing
Pytorch中tensor是索引是从0开始的
a = b[0, 3] # 从b选择第1行,第4列
Tensors还可以使用Python的切片索引
b = a[:, 3:5] # 选择所有行,第4和第5列
No Camel Casing 无驼峰拼写法
所有的函数名都不再采用驼峰拼写法. 例如 indexAdd 现在改写为 index_add_
x = torch.ones(5, 5);
# tensor([[ 1., 1., 1., 1., 1.],
# [ 1., 1., 1., 1., 1.],
# [ 1., 1., 1., 1., 1.],
# [ 1., 1., 1., 1., 1.],
# [ 1., 1., 1., 1., 1.]])
z = torch.empty(5, 2)
z[:, 0] = 10
z[:, 1] = 100
# tensor([[ 10., 100.],
# [ 10., 100.],
# [ 10., 100.],
# [ 10., 100.],
# [ 10., 100.]])
x.index_add_(1, torch.tensor([4, 0]), z)
# 在x的第一维方向(水平方向), x的第五列(索引为4)加z的第一列,x的第一列(索引为0)加z的第二列
# tensor([[ 101., 1., 1., 1., 11.],
# [ 101., 1., 1., 1., 11.],
# [ 101., 1., 1., 1., 11.],
# [ 101., 1., 1., 1., 11.],
# [ 101., 1., 1., 1., 11.]])
Numpy 桥
Numpy array 和 torch Tensor之间的转换非常简单,两者之间会共享内存地址,即改变一个另一个也会随之改变.
把torch Tensor 转换成numpy Array
a = torch.ones(5)
# tensor([ 1., 1., 1., 1., 1.])
b = a.numpy()
# [1. 1. 1. 1. 1.]
a.add_(1)
# tensor([ 2., 2., 2., 2., 2.])
# [2. 2. 2. 2. 2.]
把numpy Array 转换成torch Tensor
a = np.ones(5)
b = torch.from_numpy(a)
# [1. 1. 1. 1. 1.]
# tensor([ 1., 1., 1., 1., 1.], dtype=torch.float64)
CUDA Tensors
在Pytorch中CUDA Tensors简单好用,从CPU转换一个CUDA Tensors到GPU会保存其原始类型
# Let us run this cell only cuda is available
if torch.cuda.is_available():
# create a LongTensor and transfer it
# to GPU as torch.cuda.LongTensor
a = torch.full((10, ), 2, device=torch.device("cuda"))
print(a)
b = a.to(torch.device("cpu"))
# transfer it to CPU, back to
# being a torch.LongTensor