张量(Tensors)

5 阅读5分钟

张量(Tensors)

张量(Tensor)是一种特殊的数据结构,与数组和矩阵非常相似。在 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) # 保留 x_data 的属性
print(f"全1张量: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # 覆盖 x_data 的数据类型
print(f"随机张量: \n {x_rand} \n")
输出结果
1张量:
 tensor([[1, 1],
        [1, 1]])

随机张量:
 tensor([[0.5416, 0.6049],
        [0.6855, 0.0285]])

使用随机值或常量值创建

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

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

print(f"随机张量: \n {rand_tensor} \n")
print(f"全1张量: \n {ones_tensor} \n")
print(f"全0张量: \n {zeros_tensor}")
输出结果
随机张量:
 tensor([[0.3900, 0.2011, 0.3416],
        [0.8625, 0.8022, 0.2033]])

全1张量:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

全0张量:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

张量属性

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

tensor = torch.rand(3, 4)

print(f"张量形状: {tensor.shape}")
print(f"张量数据类型: {tensor.dtype}")
print(f"张量存储设备: {tensor.device}")
输出结果
张量形状: torch.Size([3, 4])
张量数据类型: torch.float32
张量存储设备: cpu

张量操作

PyTorch 提供了超过 100 种张量操作,包括转置、索引、切片、数学运算、线性代数、随机采样等,完整列表可参考官方文档

这些操作都可以在 GPU 上运行(速度通常比 CPU 快)。如果你使用 Colab,可以通过「Edit > Notebook Settings」分配 GPU。

# 如果有可用的 GPU,将张量移到 GPU 上
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"张量存储设备: {tensor.device}")
输出结果
张量存储设备: cuda:0

尝试使用列表中的一些操作。如果你熟悉 NumPy API,会发现 Tensor API 非常容易使用。

标准的 NumPy 风格索引和切片

tensor = torch.ones(4, 4)
tensor[:,1] = 0  # 将第二列(索引1)全部设为0
print(tensor)
输出结果
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

拼接张量

可以使用 torch.cat 沿指定维度拼接一系列张量。另一个张量拼接操作 torch.stacktorch.cat 略有不同,可自行了解。

t1 = torch.cat([tensor, tensor, tensor], dim=1) # 沿列维度(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.]])

张量乘法

# 按元素相乘
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# 等效语法
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")
# 等效语法
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.]])

原地操作

后缀为 _ 的操作是原地操作(in-place)。例如:x.copy_(y)x.t_() 会修改 x 本身。

print(tensor, "\n")
tensor.add_(5) # 原地加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.450 秒

总结

  1. PyTorch 张量是类似 NumPy 数组的高性能数据结构,核心优势是支持 GPU 加速和自动微分,是深度学习的基础数据载体;
  2. 张量支持多种初始化方式(直接创建、从NumPy转换、从其他张量创建、随机/常量创建),以及丰富的操作(索引、拼接、乘法、原地操作等);
  3. CPU 张量与 NumPy 数组共享内存,修改一方会同步影响另一方;原地操作虽节省内存,但可能影响梯度计算,不建议使用。