【深度学习 Pytorch系列课程】PyTorch Tensor编程教学:基础与实战
·
⚙️ 一、Tensor创建方法
-
基础创建
- 从数据构造:
# 从列表创建 t1 = torch.tensor([[1, 2], [3, 4]]) # 从NumPy共享内存创建 np_arr = np.array([5, 6]) t2 = torch.from_numpy(np_arr) # 修改np_arr会同步修改t2 - 特殊初始化:
zeros = torch.zeros(2, 3) # 全零张量 ones = torch.ones(2, 3) # 全一张量 rand_tensor = torch.rand(2, 3) # [0,1)均匀分布 randn_tensor = torch.randn(2, 3) # 标准正态分布
- 从数据构造:
-
序列与特殊张量
arange = torch.arange(0, 10, 2) # 等差序列:tensor([0, 2, 4, 6, 8]) linspace = torch.linspace(0, 1, 5) # 线性等分:tensor([0.0, 0.25, 0.5, 0.75, 1.0]) identity = torch.eye(3) # 3x3单位矩阵
📊 二、Tensor属性查看
| 属性 | 说明 | 示例代码 |
|---|---|---|
.shape | 张量形状 | tensor.shape → torch.Size([2,3]) |
.dtype | 数据类型 | tensor.dtype → torch.float32 |
.device | 存储设备 | tensor.device → cuda:0 |
.requires_grad | 是否可求导 | tensor.requires_grad = True |
.ndim | 维度数(秩) | tensor.ndim → 2 |
➕ 三、Tensor数学运算
-
逐元素运算
a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) # 加法 c = a + b # 等价于 torch.add(a, b) # 乘法(逐元素) d = a * b # tensor([4, 10, 18]) # 指数运算 e = a ** 2 # tensor([1, 4, 9]) -
矩阵运算
mat1 = torch.randn(2, 3) mat2 = torch.randn(3, 2) # 矩阵乘法 matmul = torch.mm(mat1, mat2) # 或 mat1 @ mat2 # 批量矩阵乘法(3D张量) batch1 = torch.randn(32, 10, 20) batch2 = torch.randn(32, 20, 30) batch_matmul = torch.bmm(batch1, batch2) # shape: (32, 10, 30)
🔀 四、形状操作与索引
-
形状变换
x = torch.arange(6) # tensor([0, 1, 2, 3, 4, 5]) # 重塑形状(不复制数据) y = x.view(2, 3) # tensor([[0, 1, 2], [3, 4, 5]]) # 压缩/扩展维度 z = torch.unsqueeze(y, 0) # shape: [1, 2, 3] w = torch.squeeze(z) # 移除所有长度为1的维度 -
高级索引
t = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 布尔索引 mask = t > 3 selected = t[mask] # tensor([4, 5, 6]) # Gather操作(按索引采集) index = torch.tensor([[0, 1], [1, 0]]) gathered = torch.gather(t, 1, index) # tensor([[1, 2], [5, 4]])
🧩 五、广播机制与归并操作
-
广播规则
- 规则:小维度张量自动扩展以匹配大维度张量。
a = torch.tensor([[1], [2]]) # shape: [2, 1] b = torch.tensor([10, 20, 30]) # shape: [3] c = a + b # 广播后:a扩展为[2,3], b扩展为[2,3] → tensor([[11,21,31], [12,22,32]]) -
归并操作
x = torch.tensor([[1, 2], [3, 4]]) # 沿维度求和 sum_dim0 = torch.sum(x, dim=0) # tensor([4, 6]) # 最大值索引 max_val, max_idx = torch.max(x, dim=1) # values: tensor([2, 4]), indices: tensor([1, 1])
⚠️ 六、关键注意事项
-
视图(View) vs 复制(Copy)
view()返回共享数据存储的视图,修改会影响原张量。reshape()可能返回视图或复制(当连续性不满足时)。
-
Inplace操作
- 后缀
_的操作(如add_())会修改原张量,节省内存但破坏计算图:a = torch.tensor([1, 2]) a.add_(1) # a变为 [2, 3]
- 后缀
-
数据类型转换
a = torch.tensor([1, 2], dtype=torch.int32) b = a.float() # 转为float32 → tensor([1., 2.]) # 需显式赋值:c = a.to(torch.float32) 否则原张量不变
🚀 七、实战应用场景
-
神经网络权重初始化
conv_weight = torch.randn(64, 3, 3, 3) # 卷积层权重 fc_weight = torch.zeros(100, 512) # 全连接层初始化为零 -
数据预处理
# 图像归一化 (批量操作) images = torch.randn(32, 3, 224, 224) normalized = (images - images.mean()) / images.std() -
自动微分支持
x = torch.tensor(2.0, requires_grad=True) y = x**2 + 3*x + 1 y.backward() # 计算梯度 print(x.grad) # 输出: 7.0 (dy/dx = 2x+3)
💎 核心总结表
| 操作类型 | 常用函数/方法 | 关键用途 |
|---|---|---|
| 创建 | tensor(), rand(), arange() | 从数据/分布生成张量 |
| 属性查看 | .shape, .dtype, .device | 获取张量元信息 |
| 数学运算 | +, *, @, mm(), bmm() | 标量/矩阵/批量矩阵运算 |
| 形状操作 | view(), unsqueeze(), permute() | 改变维度结构 |
| 索引切片 | gather(), masked_select() | 按条件提取数据 |
| 归并与广播 | sum(), max() + 自动广播 | 聚合数据与维度扩展 |
学习建议:
- 边用边查:掌握常用操作后,通过https://pytorch.org/docs深化理解。
- 调试技巧:使用
print(tensor.shape)和tensor.device快速定位维度/设备错误。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)