PyTorch 基础入门:张量(Tensor)
🔥 什么是张量?
张量(Tensor)是 PyTorch 的核心数据结构,你可以把它理解为可以在 GPU 上加速运算的多维数组。它和 NumPy 的 ndarray 非常相似,但多了三个关键能力:
- 自动求导(Autograd)——自动计算梯度
- GPU 加速——张量可以搬到 GPU 上,实现百倍级提速
- 动态计算图——每次前向传播都是一张新图,调试方便
| 术语 | 维度 | 示例 |
|---|---|---|
| 标量(Scalar) | 0 维 | torch.tensor(3.14) |
| 向量(Vector) | 1 维 | torch.tensor([1, 2, 3]) |
| 矩阵(Matrix) | 2 维 | torch.randn(3, 4) |
| 张量(Tensor) | ≥3 维 | torch.randn(2, 3, 4, 5) |
📦 创建张量
importtorchimportnumpyasnp从数据创建
# 从列表x=torch.tensor([1,2,3])# tensor([1, 2, 3])# 从嵌套列表(2D)x=torch.tensor([[1,2],[3,4],[5,6]])# tensor([[1, 2],# [3, 4],# [5, 6]])# 从 NumPy 数组arr=np.array([1,2,3])x=torch.from_numpy(arr)# 共享内存x=torch.tensor(arr)# 复制数据# 指定数据类型x=torch.tensor([1,2,3],dtype=torch.float32)特殊张量
# 全零 / 全一x=torch.zeros(3,4)# (3, 4) 的全零矩阵x=torch.ones(3,4)# (3, 4) 的全一矩阵x=torch.zeros_like(y)# 和 y 形状相同的全零# 单位矩阵x=torch.eye(3)# 3x3 单位矩阵# 未初始化(效率更高,但需立即赋值)x=torch.empty(3,4)# 全填充x=torch.full((3,4),7)# 全为 7 的 (3, 4) 矩阵序列张量
# 等差x=torch.arange(0,10,2)# tensor([0, 2, 4, 6, 8])x=torch.arange(5)# tensor([0, 1, 2, 3, 4])# 等分x=torch.linspace(0,1,5)# 0 到 1 均匀取 5 个点# tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])# 对数等分x=torch.logspace(-2,2,5)# 10^-2 到 10^2随机张量 ⭐
# 均匀分布 [0, 1)x=torch.rand(3,4)# 标准正态分布 N(0, 1)x=torch.randn(3,4)# 整数随机 [low, high)x=torch.randint(0,10,(3,4))# 正态分布 N(mean, std)x=torch.normal(mean=0,std=1,size=(3,4))# 随机排列x=torch.randperm(10)# 0-9 的随机排列# 固定随机种子(可复现)torch.manual_seed(42)📐 张量属性
x=torch.randn(2,3,4)print(x.shape)# torch.Size([2, 3, 4])print(x.size())# 同上,可以传入 dim: x.size(0) → 2print(x.ndim)# 维度数: 3print(x.dtype)# 数据类型: torch.float32print(x.device)# 所在设备: cpu / cuda:0print(x.numel())# 总元素数: 24print(x.requires_grad)# 是否需要梯度🔢 数据类型(dtype)
| 类型 | 别名 | 说明 |
|---|---|---|
torch.float32 | torch.float | 32 位浮点(默认) |
torch.float64 | torch.double | 64 位双精度 |
torch.float16 | torch.half | 16 位半精度 |
torch.int64 | torch.long | 64 位整数 |
torch.int32 | torch.int | 32 位整数 |
torch.int8 | — | 8 位整数(量化用) |
torch.bool | — | 布尔型 |
torch.bfloat16 | — | Brain 浮点(训练用) |
# 类型转换x=torch.tensor([1,2,3],dtype=torch.int64)x=x.float()# → float32x=x.double()# → float64x=x.to(torch.float16)# → float16x=x.type(torch.int32)# → int32# 创建时指定x=torch.tensor([1.0,2.0],dtype=torch.float64)⚙️ 基本运算
算术运算
a=torch.tensor([1,2,3],dtype=torch.float32)b=torch.tensor([4,5,6],dtype=torch.float32)# 逐元素运算(支持广播)print(a+b)# tensor([5., 7., 9.])print(a-b)# tensor([-3., -3., -3.])print(a*b)# tensor([4., 10., 18.]) 逐元素乘法!print(a/b)# tensor([0.2500, 0.4000, 0.5000])print(a**2)# tensor([1., 4., 9.])# 原地操作(名称后带 _ 下划线)a.add_(1)# a += 1,直接修改 aa.mul_(2)# a *= 2矩阵运算
A=torch.randn(3,4)B=torch.randn(4,5)# 矩阵乘法C=A @ B# 推荐写法C=torch.mm(A,B)# 只支持 2DC=torch.matmul(A,B)# 支持广播# 批矩阵乘法A=torch.randn(10,3,4)# batch=10B=torch.randn(10,4,5)C=torch.bmm(A,B)# (10, 3, 5)# 转置print(A.T)# 2D 转置print(A.transpose(0,1))# 交换两个维度print(A.permute(1,0,2))# 任意维度重排# 点积 / 外积v1,v2=torch.randn(3),torch.randn(3)dot=torch.dot(v1,v2)# 内积(点积)outer=torch.outer(v1,v2)# 外积统计运算
x=torch.randn(3,4)print(x.sum())# 所有元素求和print(x.sum(dim=0))# 沿行求和(压缩行)→ (4,)print(x.sum(dim=1))# 沿列求和(压缩列)→ (3,)print(x.mean())# 均值print(x.std())# 标准差print(x.var())# 方差print(x.max())# 最大值print(x.min())# 最小值print(x.argmax())# 最大值索引(展平后)print(x.argmax(dim=1))# 每行最大值索引 → (3,)比较运算
x=torch.tensor([1,2,3,4,5])print(x>3)# tensor([False, False, False, True, True])print(x==3)# tensor([False, False, True, False, False])print((x>2)&(x<5))# tensor([False, False, True, True, False])print(torch.any(x>3))# Trueprint(torch.all(x>0))# True🎯 索引与切片
x=torch.randn(4,5)# 基本索引print(x[0])# 第 0 行 → (5,)print(x[0,1])# 第 0 行第 1 列 → 标量print(x[:,0])# 第 0 列 → (4,)# 切片print(x[:2])# 前 2 行print(x[1:3,2:4])# 行 1-2, 列 2-3print(x[::2])# 每隔一行# 高级索引indices=torch.tensor([0,2,3])print(x[indices])# 取第 0, 2, 3 行print(x[[0,2],[1,3]])# 取 (0,1) 和 (2,3) 两个元素# 布尔索引mask=x>0print(x[mask])# 所有 >0 的元素(展平为一维)🔧 形状操作
x=torch.randn(2,3,4)# view / reshapey=x.view(-1,4)# 自动推导第一维 → (6, 4)y=x.reshape(6,4)# 同上,但 view 要求内存连续# 升维 / 降维y=x.unsqueeze(0)# 在第 0 维前插入 → (1, 2, 3, 4)y=x.unsqueeze(-1)# 在最后一维后插入 → (2, 3, 4, 1)y=x.squeeze()# 删除所有长度为 1 的维度# 展平y=x.flatten()# 完全展平 → (24,)y=x.flatten(start_dim=1)# 从第 1 维开始展平 → (2, 12)# 拼接与堆叠a,b=torch.randn(2,3),torch.randn(2,3)c=torch.cat([a,b],dim=0)# 沿 dim=0 拼接 → (4, 3)c=torch.cat([a,b],dim=1)# 沿 dim=1 拼接 → (2, 6)c=torch.stack([a,b],dim=0)# 新维度堆叠 → (2, 2, 3)# 分割chunks=torch.chunk(x,chunks=3,dim=1)# 均分为 3 块parts=torch.split(x,split_size_or_sections=2,dim=0)# 每块 2 行↔️ NumPy 互转
# Tensor → NumPyx=torch.randn(3,4)arr=x.numpy()# CPU 上直接转换(共享内存!)arr=x.cpu().detach().numpy()# GPU 张量安全转换# NumPy → Tensorarr=np.array([1,2,3])x=torch.from_numpy(arr)# 共享内存x=torch.tensor(arr)# 复制一份新数据⚠️
torch.from_numpy()和张量调用.numpy()是共享内存的,改一个另一个也会变!
🖥️ 设备管理
# 查看可用设备print(torch.cuda.is_available())# 是否有 GPUprint(torch.cuda.device_count())# GPU 数量# 创建时指定设备x=torch.randn(3,4,device='cuda')# 直接在 GPU 上创建x=torch.randn(3,4,device='cuda:0')# 指定 GPU 编号# 移动张量x=x.to('cuda')# 移到 GPUx=x.cuda()# 同上x=x.to('cpu')# 移回 CPUx=x.cpu()# 同上# 设备无关代码device=torch.device('cuda'iftorch.cuda.is_available()else'cpu')x=torch.randn(3,4).to(device)📝 速查表
| 需求 | 代码 |
|---|---|
| 创建列表张量 | torch.tensor([1, 2, 3]) |
| 全零 | torch.zeros(3, 4) |
| 全一 | torch.ones(3, 4) |
| 标准正态随机 | torch.randn(3, 4) |
| 均匀随机 | torch.rand(3, 4) |
| 等差数列 | torch.arange(0, 10, 2) |
| 等分数列 | torch.linspace(0, 1, 10) |
| 矩阵乘法 | A @ B |
| 转置 | x.T/x.transpose(0, 1) |
| 改变形状 | x.view(-1, 4)/x.reshape(6, 4) |
| 插入维度 | x.unsqueeze(0) |
| 删除1维 | x.squeeze() |
| 展平 | x.flatten() |
| 拼接 | torch.cat([a, b], dim=0) |
| 堆叠 | torch.stack([a, b], dim=0) |
| 沿轴求和 | x.sum(dim=0) |
| NumPy→Tensor | torch.from_numpy(arr) |
| Tensor→NumPy | x.numpy() |
| 移到GPU | x.to('cuda') |
| 数据类型 | x.float()/x.long() |
[[pytorch-总览|← 返回总览]]