PyTorch 入门指南
学习 PyTorch
图像和视频
音频
后端
强化学习
在生产环境中部署 PyTorch 模型
Profiling PyTorch
代码变换与FX
前端API
扩展 PyTorch
模型优化
并行和分布式训练
边缘端的 ExecuTorch
推荐系统
多模态

基础知识 || 快速入门 || 张量 || 数据集与数据加载器 || 变换 || 构建模型 || 自动求导 || 优化 || 保存与加载模型

张量

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

张量与 NumPy 的 ndarrays 类似,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。实际上,张量和 NumPy 数组通常可以共享相同的内存,从而无需复制数据(参见 与 NumPy 的桥接)。张量还针对自动微分进行了优化(我们将在 Autograd 部分中详细介绍)。如果您熟悉 ndarrays,那么您将很容易上手张量 API。如果不熟悉,请继续阅读!

importtorch
importnumpyasnp
Plain text

初始化张量

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

直接从数据创建

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

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

从 NumPy 数组创建

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

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

从另一个张量创建:

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

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")
Plain text
Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.8823, 0.9150],
        [0.3829, 0.9593]])
Plain text

使用随机或常量值:

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}")
Plain text
Random Tensor:
 tensor([[0.3904, 0.6009, 0.2566],
        [0.7936, 0.9408, 0.1332]])

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

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

张量的属性

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

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}")
Plain text
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
Plain text

张量操作

超过 1200 种张量操作,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等,在这里有全面描述。

这些操作中的每一个都可以在 CPU 和加速器(如 CUDA、MPS、MTIA 或 XPU)上运行。如果您使用 Colab,可以通过转到 Runtime > Change runtime type > GPU 来分配加速器。

默认情况下,张量是在 CPU 上创建的。我们需要在确认加速器可用后,使用 .to 方法显式地将张量移动到加速器。请注意,跨设备复制大型张量在时间和内存方面可能会非常昂贵!

# We move our tensor to the current accelerator if available
if torch.accelerator.is_available():
    tensor = tensor.to(torch.accelerator.current_accelerator())
Plain text

尝试一些列表中的操作。如果您熟悉 NumPy API,您会发现 Tensor API 使用起来非常轻松。

类似 NumPy 的标准索引和切片操作:

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:,0]}")
print(f"Last column: {tensor[...,-1]}")
tensor[:,1] = 0
print(tensor)
Plain text
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
Plain text

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

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
Plain text
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.]])
Plain text

算术运算

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
Plain text
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
Plain text

单元素张量 如果您有一个单元素张量,例如将张量的所有值聚合为一个值,您可以使用 item() 将其转换为 Python 数值:

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
Plain text
12.0 <class 'float'>
Plain text

原地操作 将结果存储到操作数中的操作称为原地操作。它们以 _ 后缀表示。例如:x.copy_(y)x.t_() 将会改变 x

print(f"{tensor}\n")
tensor.add_(5)
print(tensor)
Plain text
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.]])
Plain text

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

与 NumPy 的桥梁

CPU 上的张量和 NumPy 数组可以共享它们的基础内存位置,修改其中一个会改变另一个。

将 Tensor 转换为 NumPy 数组

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

张量的变化会反映在 NumPy 数组中。

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

NumPy 数组转换为 Tensor

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

NumPy 数组的变化会反映在张量中。

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