Tensors
Tensor类似与NumPy的ndarray,唯一的区别是Tensor可以在GPU上加速运算。
构建Tensor
- 导入
from __future__ import print_function
import torch
- 构造未初始化的5x3矩阵
x = torch.empty(5, 3)
print(x)
- 构建一个随机初始化的5x3矩阵
x = torch.rand(5, 3)
print(x)
- 构建一个全部为0,类型为long的矩阵
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
- 从数据直接直接构建tensor
x = torch.tensor([5.5, 3])
print(x)
- 从一个已有的tensor构建一个tensor。这些方法会重用原来tensor的特征,例如,数据类型,除非提供新的数据。
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same size
- 得到tensor的形状
print(x.size())
torch.Size
返回的是一个元组(tuple)
Tensor运算
- 加法运算
y = torch.rand(5, 3)
print(x + y)
- 另一种着加法的写法
print(torch.add(x, y))
- 把输出作为一个变量
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
- in-place加法
# adds x to y
y.add_(x)
print(y)
任何in-place的运算都会以
_
结尾。 举例来说:x.copy_(y)
,x.t_()
, 会改变x
。
- 各种类似NumPy的indexing都可以在PyTorch tensor上面使用
print(x)
print(x[:, 1])
- 如果你希望
resize/reshape
一个tensor
,可以使用torch.view
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
- 如果你有一个只有一个元素的tensor,使用.item()方法可以把里面的value变成Python数值。
x = torch.randn(1)
print(x)
print(x.item())
- 各种Tensor operations, 包括transposing, indexing, slicing, mathematical operations, linear algebra, random numbers
https://pytorch.org/docs/torch
Numpy和Tensor之间的转化
在Torch Tensor和NumPy array之间相互转化非常容易。
Torch Tensor和NumPy array会共享内存,所以改变其中一项也会改变另一项。
- 把Torch Tensor转变成NumPy Array
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
- 改变numpy array里面的值
a.add_(1)
print(a)
print(b)
- 把NumPy array转成Torch Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
所有CPU上的Tensor都支持转成numpy或者从numpy转成Tensor
CUDA Tensors
使用.to
方法,Tensor
可以被移动到别的device
上。
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
如果tensor在GPU上,无法使用转换为numpy。