评价此页

张量#

创建时间:2017年3月24日 | 最后更新:2024年1月16日 | 最后验证:2024年11月05日

张量(Tensors)是一种专门的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。

张量与 NumPy 的 ndarrays 类似,不同之处在于张量可以在 GPU 或其他专用硬件上运行以加速计算。如果您熟悉 ndarrays,那么使用 Tensor API 会感到很轻松。如果不熟悉,请跟随本快速 API 教程。

import torch
import numpy as np

张量初始化#

张量可以通过多种方式进行初始化。请看以下示例:

直接从数据创建

张量可以直接从数据创建。数据类型会自动推断。

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

从 NumPy 数组创建

张量可以从 NumPy 数组创建(反之亦然,请参见 与 NumPy 的桥接)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

从另一个张量创建

新张量将保留参数张量的属性(形状、数据类型),除非被显式覆盖。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.0706, 0.5387],
        [0.1279, 0.4793]])

使用随机或常数值创建

shape 是一个张量维度的元组。在下面的函数中,它决定了输出张量的维度。

shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
Random Tensor:
 tensor([[0.0283, 0.1062, 0.8323],
        [0.7656, 0.7541, 0.6441]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

张量属性#

张量属性描述了它们的形状、数据类型以及存储它们的设备。

tensor = torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

张量运算#

超过 100 种张量运算,包括转置、索引、切片、数学运算、线性代数、随机采样等,详见 此处

它们中的每一种都可以运行在 GPU 上(通常比在 CPU 上速度更快)。如果您使用 Colab,可以通过“编辑”>“笔记本设置”来分配 GPU。

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"Device tensor is stored on: {tensor.device}")
Device tensor is stored on: cuda:0

尝试列表中的一些运算。如果您熟悉 NumPy API,您会发现 Tensor API 非常易于使用。

标准的类 NumPy 索引和切片

tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

连接张量 您可以使用 torch.cat 在指定维度上连接一系列张量。另请参阅 torch.stack,这是另一种张量连接操作,与 torch.cat 有细微差别。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

张量乘法

# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
print(f"tensor * tensor \n {tensor * tensor}")
tensor.mul(tensor)
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor * tensor
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

计算两个张量之间的矩阵乘法。

print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
tensor.matmul(tensor.T)
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

tensor @ tensor.T
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

原地操作 带有 _ 后缀的操作是原地操作。例如:x.copy_(y)x.t_() 会改变 x

print(tensor, "\n")
tensor.add_(5)
print(tensor)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

注意

原地操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不建议使用它们。


与 NumPy 的桥接#

CPU 上的张量和 NumPy 数组可以共享其底层内存位置,改变其中一个会改变另一个。

张量转 NumPy 数组#

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

对张量的更改会反映在 NumPy 数组中。

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

NumPy 数组转张量#

n = np.ones(5)
t = torch.from_numpy(n)

对 NumPy 数组的更改会反映在张量中。

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

脚本总运行时间: (0 分钟 0.494 秒)