pytorch官方网站
PyTorch是一个基于Python的科学计算软件包:numpy的替代品,可使用强大的GPU功能;一个深度学习平台,具有最大的灵活性和最快的速度。
-
张量(Tensors)
与numpy的ndarrays类似,用于GPU加速计算。一个未初始化的5行3列矩阵
a = torch.empty(5,3) print(a)
输出为
一个随机初始化的5行3列矩阵a = torch.rand(5, 3) print(a)
输出为
一个5行3列,值均为0的矩阵,类型为longa = torch.zeros(5, 3, dtype=torch.long) print(a)
输出为
一个直接给定数值的张量a = torch.tensor([5.5, 3]) print(a)
输出为
根据现有的张量创建张量。 这些方法将重用输入张量的属性a = a.new_ones(5, 3, dtype=torch.double) print(a) a = torch.randn_like(a, dtype=torch.float) print(a)
输出为
print(a.size())
输出为
torch.size()是一个元祖,支持所有元祖操作
-
操作(operations)
操作有多种语法,以加法为例。A. b= torch.rand(5, 3) print(a + b) B. print(torch.add(a,b)) C.提供一个输出张量作为参数 result = torch.empty(5, 3) torch.add(x, y, out=result) print(result) D. y.add_(x) print(y)
输出均为
任何改变一个张量位置的操作都是用_固定的,即y.add_(x)会改变y的值同样可以对张量使用标准numpy操作。
如果想要更改张量的尺寸(size),使用
torch.view
x = torch.randn(4, 4) y = x.view(16) z = x.view(-1, 8) print(x.size(), y.size(), z.size())
输出为
通过.item()
可以将张量元素的值返回为python数字x = torch.randn(1) print(x) print(x.item())
输出为
Numpy bridge
Torch Tensor和NumPy阵列将共享其底层内存位置,更改一个将改变另一个将tensor转为numpy
a = torch.ones(5) print(a) b = a.numpy() print(b) a.add_(1) print(a) print(b)
输出为
将numpy转为tensor -
CUDA Tensors
通过.to
方法移动Tensors
使用torch.device
将Tensors移入或移出GPUx = torch.rand(3,2) if torch.cuda.is_available(): device = torch.device("cuda") y = torch.ones_like(x, device=device) x = x.to(device) z = x + y print(z) print(z.to("cpu", torch.double))
输出为