数据操作

首先,我们导入 torch。请注意,虽然它被称为PyTorch,但我们应该导入 torch 而不是 pytorch

In [1]:
import torch

张量表示由一个数值组成的数组,这个数组可能有多个维度

In [2]:
x = torch.arange(12)
x
Out[2]:
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

可以通过张量的 shape 属性来访问张量的形状 和张量中元素的总数

In [3]:
x.shape
Out[3]:
torch.Size([12])
In [4]:
x.numel()
Out[4]:
12

要改变一个张量的形状而不改变元素数量和元素值,可以调用 reshape 函数

In [5]:
X = x.reshape(3, 4)
X
Out[5]:
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])

使用全0、全1、其他常量或者从特定分布中随机采样的数字

In [6]:
torch.zeros((2, 3, 4))
Out[6]:
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
In [7]:
torch.ones((2, 3, 4))
Out[7]:
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.]]])
In [8]:
torch.randn(3, 4)
Out[8]:
tensor([[ 0.2104,  1.4439, -1.3455, -0.8273],
        [ 0.8009,  0.3585, -0.2690,  1.6183],
        [-0.4611,  1.5744, -0.4882, -0.5317]])

通过提供包含数值的 Python 列表(或嵌套列表)来为所需张量中的每个元素赋予确定值

In [9]:
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
Out[9]:
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])

常见的标准算术运算符(+-*/**)都可以被升级为按元素运算

In [10]:
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x**y
Out[10]:
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))

按按元素方式应用更多的计算

In [11]:
torch.exp(x)
Out[11]:
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])

我们也可以把多个张量 连结(concatenate) 在一起

In [12]:
X = torch.arange(12, dtype=torch.float32).reshape((3, 4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
Out[12]:
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [ 2.,  1.,  4.,  3.],
         [ 1.,  2.,  3.,  4.],
         [ 4.,  3.,  2.,  1.]]),
 tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))

通过 逻辑运算符 构建二元张量

In [13]:
X == Y
Out[13]:
tensor([[False,  True, False,  True],
        [False, False, False, False],
        [False, False, False, False]])

对张量中的所有元素进行求和会产生一个只有一个元素的张量

In [14]:
X.sum()
Out[14]:
tensor(66.)

即使形状不同,我们仍然可以通过调用 广播机制 (broadcasting mechanism) 来执行按元素操作

In [15]:
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
Out[15]:
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
In [16]:
a + b
Out[16]:
tensor([[0, 1],
        [1, 2],
        [2, 3]])

可以用 [-1] 选择最后一个元素,可以用 [1:3] 选择第二个和第三个元素

In [17]:
X[-1], X[1:3]
Out[17]:
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))

除读取外,我们还可以通过指定索引来将元素写入矩阵

In [18]:
X[1, 2] = 9
X
Out[18]:
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  9.,  7.],
        [ 8.,  9., 10., 11.]])

为多个元素赋值相同的值,我们只需要索引所有元素,然后为它们赋值

In [19]:
X[0:2, :] = 12
X
Out[19]:
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])

运行一些操作可能会导致为新结果分配内存

In [20]:
before = id(Y)
Y = Y + X
id(Y) == before
Out[20]:
False

执行原地操作

In [21]:
Z = torch.zeros_like(Y)
print('id(Z):', id(Z))
Z[:] = X + Y
print('id(Z):', id(Z))
id(Z): 140452400950336
id(Z): 140452400950336

如果在后续计算中没有重复使用 X,我们也可以使用 X[:] = X + YX += Y 来减少操作的内存开销

In [22]:
before = id(X)
X += Y
id(X) == before
Out[22]:
True

转换为 NumPy 张量

In [23]:
A = X.numpy()
B = torch.tensor(A)
type(A), type(B)
Out[23]:
(numpy.ndarray, torch.Tensor)

将大小为1的张量转换为 Python 标量

In [24]:
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
Out[24]:
(tensor([3.5000]), 3.5, 3.5, 3)