搜索

pdf文档 深度学习与PyTorch入门实战 - 12. 数学运算

1015.16 KB 11 页 1 下载 58 浏览 0 评论 0 收藏
语言 格式 评分
中文(简体)
.pdf
3
摘要
文档介绍了PyTorch中的基本数学运算,包括加减乘除、矩阵乘法(matmul)、幂运算(pow)、平方根(sqrt/rsqrt)和四舍五入(round)等操作。通过代码示例展示了矩阵乘法的实现方式(如torch.mm和torch.matmul),并演示了如何使用这些运算进行张量操作。文档还涉及了张量的形状、广播机制以及近似函数(如floor、ceil、trunc、frac)的使用。
AI总结
### 深度学习与PyTorch入门实战 - 数学运算总结 #### 1. 基本运算 PyTorch支持常见的数学运算,包括: - **加法/减法/乘法/除法**:基础的算术运算。 - **幂运算**:`torch.pow` 或 `**`。 - **平方根/倒数平方根**:`torch.sqrt` 和 `torch.rsqrt`。 - **四舍五入**:`torch.round`。 #### 2. 矩阵乘法 - **`torch.mm`**:仅适用于2D张量。 - **`torch.matmul`** 和 `@`:支持多维张量的矩阵乘法。 - 示例: ```python a = torch.tensor([[3., 3.], [3., 3.]]) b = torch.ones(2,2) print(torch.mm(a, b)) # 输出:tensor([[6., 6.], [6., 6.]]) print(torch.matmul(a, b)) # 输出:tensor([[6., 6.], [6., 6.]]) print(a @ b) # 输出:tensor([[6., 6.], [6., 6.]]) ``` - 多维张量的矩阵乘法需注意张量维度的匹配。 #### 3. 幂运算与平方根 - **幂运算**:`a.pow(2)` 或 `a**2`。 - **平方根**:`a.sqrt()`。 - **倒数平方根**:`a.rsqrt()`。 #### 4. 夹紧操作(Clamp) - **`torch.clamp`**:用于限制张量的值范围,常用于梯度截断。 - 示例: ```python grad = torch.rand(2,3)*15 print(grad.max()) # 输出:tensor(14.8737) print(grad.clamp(0, 10)) # 输出:tensor([[10.0000, 10.0000, 4.4872], [10.0000, 8.9101, 10.0000]]) ``` #### 5. 近似函数 - **`torch.floor()`**:向下取整。 - **`torch.ceil()`**:向上取整。 - **`torch.round()`**:四舍五入。 - **`torch.trunc()`**:截断到整数部分。 - **`torch.frac()`**:返回小数部分。 #### 6. 示例 - **幂运算与平方根**: ```python a = torch.full([2,2],3) print(a.pow(2)) # 输出:tensor([[9., 9.], [9., 9.]]) print(a**2) # 输出:tensor([[9., 9.], [9., 9.]]) print(a.sqrt()) # 输出:tensor([[3., 3.], [3., 3.]]) print(a.rsqrt()) # 输出:tensor([[0.3333, 0.3333], [0.3333, 0.3333]]) ``` - **四舍五入**: ```python a = torch.tensor(3.5) print(a.round()) # 输出:tensor(4.) ``` #### 7. 总结 PyTorch提供了丰富的数学运算功能,支持基本的算术运算、矩阵乘法、幂运算、平方根、夹紧操作和近似函数。这些功能在深度学习模型的构建和训练中非常常用,掌握这些操作可以帮助开发者更高效地进行模型开发和优化。
P1
P2
P3
P4
P5
P6
P7
下载文档到本地,方便使用
- 可预览页数已用完,剩余 4 页请下载阅读 -
文档评分
请文明评论,理性发言.