注意
跳转到结尾 以下载完整的示例代码。
学习基础知识 || 快速入门 || 张量 || 数据集 & 数据加载器 || 变换 || 构建模型 || 自动梯度 || 优化 || 保存 & 加载模型
张量#
创建日期:2021 年 2 月 10 日 | 最后更新:2025 年 1 月 24 日 | 最后验证:2024 年 11 月 5 日
张量是一种专门的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。
张量类似于 NumPy 的 ndarrays,但张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据(请参阅 与 NumPy 桥接)。张量也针对自动微分进行了优化(我们稍后将在 自动梯度 部分中了解更多信息)。如果您熟悉 ndarrays,那么使用 Tensor 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.5513, 0.5079],
[0.8693, 0.0571]])
使用随机或常量值
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.2678, 0.2952, 0.8638],
[0.5615, 0.7312, 0.6692]])
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
张量上的操作#
超过 1200 个张量操作,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等,在此处进行了全面描述 此处。
这些操作中的每一个都可以在 CPU 和 加速器(如 CUDA、MPS、MTIA 或 XPU)上运行。如果您使用的是 Colab,请通过“运行时”>“更改运行时类型”>“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())
尝试列表中的一些操作。如果您熟悉 NumPy API,您会发现 Tensor API 非常易于使用。
标准的 NumPy 风格的索引和切片
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.]])
连接张量 您可以使用 torch.cat 沿给定维度连接一系列张量。另请参阅 torch.stack,另一个张量连接运算符,它与 torch.cat 略有不同。
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 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)
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
单元素张量 如果您有一个单元素张量,例如通过将张量的所有值聚合到一个值,可以使用 item() 将其转换为 Python 数值。
12.0 <class 'float'>
原地操作 将结果存储到操作数的运算称为原地运算。它们用 _ 后缀表示。例如:x.copy_(y)、x.t_() 将更改 x。
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: 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.471 秒)