PyTorch 矩阵运算

矩阵的基本概念#

什么是矩阵?#

矩阵是一个按照矩形阵列排列的数学对象,包含两个维度。

矩阵的属性(维度概念)#

  • 0维张量:标量(单个数字) - torch.tensor(5)
  • 1维张量:向量(只有长度) - torch.tensor([1, 2, 3])
  • 2维张量:矩阵(有行和列) - torch.tensor([[1, 2], [3, 4]])
  • 3维张量:立方体(有深度) - 比如多个矩阵的堆叠
  • 更高维度:可以继续扩展

注意:在深度学习中,我们通常用张量这个更一般的概念,矩阵是2维张量的特例。

PyTorch中创建矩阵的常用函数#

1. 直接从数据创建#

import torch

# 从Python列表创建
matrix_2x3 = torch.tensor([[1, 2, 3],
                          [4, 5, 6]])
print(f"形状: {matrix_2x3.shape}")  # 输出: torch.Size([2, 3])
print(f"维度: {matrix_2x3.dim()}")   # 输出: 2

2. 创建特殊矩阵的函数#

# 全零矩阵
zeros_matrix = torch.zeros(2, 3)  # 2行3列的全0矩阵
# [[0, 0, 0],
#  [0, 0, 0]]

# 全一矩阵
ones_matrix = torch.ones(3, 2)   # 3行2列的全1矩阵

# 单位矩阵
identity = torch.eye(3)  # 3x3单位矩阵
# [[1, 0, 0],
#  [0, 1, 0],
#  [0, 0, 1]]

# 随机矩阵
random_matrix = torch.rand(2, 3)  # 2x3矩阵,元素在[0,1)均匀分布
normal_matrix = torch.randn(2, 3) # 2x3矩阵,元素服从标准正态分布

3. 创建矩阵的核心参数#

# 完整的参数列表示例
matrix = torch.tensor(
    data=[[1, 2], [3, 4]],  # 数据源
    dtype=torch.float32,     # 数据类型:int32, float64等
    device='cuda',           # 存储设备:'cpu' 或 'cuda'
    requires_grad=True       # 是否需要计算梯度(用于反向传播)
)

# 或者使用工厂函数
matrix = torch.zeros(
    size=(2, 3),            # 形状:行数, 列数
    dtype=torch.float32,
    device='cpu',
    requires_grad=False
)

矩阵操作的例子#

# 创建两个矩阵
A = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
B = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)

# 矩阵加法
C = A + B  # [[6, 8], [10, 12]]

# 矩阵乘法(注意:不是逐元素相乘)
D = torch.mm(A, B)  # 或者 A @ B
# 计算过程:
# [1*5 + 2*7, 1*6 + 2*8] = [19, 22]
# [3*5 + 4*7, 3*6 + 4*8] = [43, 50]

# 逐元素相乘
E = A * B  # [[5, 12], [21, 32]]

print(f"矩阵A形状: {A.shape}")  # torch.Size([2, 2])
print(f"矩阵A: \\\\n{A}")

在大模型中的实际应用#

回到我们之前讨论的嵌入矩阵例子:

# 模拟一个词汇表大小为50000,向量维度为768的嵌入矩阵
vocab_size = 50000
embedding_dim = 768

# 创建嵌入矩阵
embedding_matrix = torch.randn(vocab_size, embedding_dim)
print(f"嵌入矩阵形状: {embedding_matrix.shape}")  # torch.Size([50000, 768])

# 查找单词"cat"的向量(假设"cat"的索引是42)
word_index = 42
word_vector = embedding_matrix[word_index]  # 获取第42行的向量
print(f"单词向量的形状: {word_vector.shape}")  # torch.Size([768])

重要概念总结#

概念数学表示PyTorch实现说明
标量( a )torch.tensor(5)0维,单个值
向量( \begin{bmatrix}1 & 2 & 3\end{bmatrix} )torch.tensor([1,2,3])1维,只有长度
矩阵( \begin{bmatrix}1 & 2 \ 3 & 4\end{bmatrix} )torch.tensor([[1,2],[3,4]])2维,行和列
张量任意维度torch.rand(2,3,4)多维数组的通用术语

关键理解

  • 在深度学习中,矩阵就是2维张量
  • 我们之前讨论的嵌入矩阵 [50000, 768] 就是一个有50000行、768列的矩阵
  • 每一行代表一个词的向量,每一列代表向量的一个维度
本文共 1048 字,创建于 Oct 27, 2025

相关标签: PyTorch, Python, 机器学习, Math, Algorithms