备注
点击此处下载完整示例代码
张量 ¶
创建于:2025 年 4 月 1 日 | 最后更新:2025 年 4 月 1 日 | 最后验证:2024 年 11 月 5 日
张量是一种专门的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。
张量类似于 NumPy 的 ndarray,但张量可以在 GPU 或其他专用硬件上运行以加速计算。如果您熟悉 ndarray,您将很快适应 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")
使用随机或常量值:
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}")
张量属性 §
张量属性描述了它们的形状、数据类型以及它们存储的设备。
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}")
张量运算 §
这里全面介绍了超过 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}")
尝试使用列表中的某些操作。如果您熟悉 NumPy API,您会发现 Tensor API 的使用非常简单。
标准 NumPy-like 索引和切片:
tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
张量连接您可以使用 torch.cat
来沿着指定维度连接一系列张量。另见 torch.stack,这是另一种张量连接操作,与 torch.cat
略有不同。
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
张量乘法
# 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}")
这计算两个张量之间的矩阵乘法
print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
原地操作带有 _
后缀的操作是原地操作。例如: x.copy_(y)
, x.t_()
,将改变 x
。
print(tensor, "\n")
tensor.add_(5)
print(tensor)
备注
原地操作可以节省一些内存,但可能会因为立即丢失历史记录而在计算导数时出现问题。因此,不建议使用。
使用 NumPy 的桥梁
CPU 和 NumPy 数组可以共享其底层的内存位置,更改其中一个也会更改另一个。
张量转 NumPy 数组
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
张量的更改会反映在 NumPy 数组中。
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
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}")
脚本总运行时间:(0 分钟 0.000 秒)