pytorch-基本数学运算

这篇博客详细介绍了PyTorch中基本的数学运算,包括加法、减法、乘法、除法,以及矩阵乘法(matmul)、次方、开方、四舍五入等操作。通过实例展示了如何使用这些操作,并解释了不同运算在张量维度不匹配时的行为。此外,还提到了梯度裁剪、数值范围限制等实用技巧,对于理解PyTorch的张量操作非常有帮助。

基本运算

▪ Add/minus/multiply/divide

▪ Matmul

▪ Pow

▪ Sqrt/rsqrt

▪ Round

加法

import torch
a=torch.rand(3,4)
b=torch.rand(4)
a+b
tensor([[0.4990, 1.6506, 1.1205, 0.9656],
        [0.5472, 1.9627, 0.8368, 0.5020],
        [0.6576, 1.1725, 0.8564, 1.0940]])
    torch.add(a, b)
tensor([[0.4990, 1.6506, 1.1205, 0.9656],
        [0.5472, 1.9627, 0.8368, 0.5020],
        [0.6576, 1.1725, 0.8564, 1.0940]])
torch.all(torch.eq(a-b, torch.sub(a,b)))
tensor(True)
torch.all(torch.eq(a*b, torch.mul(a,b)))
tensor(True)
torch.all(torch.eq(a/b, torch.div(a,b)))
tensor(True)

乘法

a = torch.tensor([[3.,3.],[3.,3.]])
a
tensor([[3., 3.],
        [3., 3.]])
b=torch.ones(2,2)
b
tensor([[1., 1.],
        [1., 1.]])
torch.mm(a,b) # only for 2d
tensor([[6., 6.],
        [6., 6.]])
torch.matmul(a,b)
tensor([[6., 6.],
        [6., 6.]])
a@b
tensor([[6., 6.],
        [6., 6.]])

An example of matmul

a=torch.rand(4, 784)
x=torch.rand(4, 784)
w=torch.rand(512, 784)
# [4,784] @ [512,784].t() => [4,784] @ [784, 512]
(x@w.t()).shape
torch.Size([4, 512])
a=torch.rand(4,3,28,64)
b=torch.rand(4,3,64,32)
torch.mm(a,b).shape  # only for 2d
---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

<ipython-input-23-2699c069c540> in <module>
      1 a=torch.rand(4,3,28,64)
      2 b=torch.rand(4,3,64,32)
----> 3 torch.mm(a,b).shape


RuntimeError: matrices expected, got 4D, 4D tensors at ..\aten\src\TH/generic/THTensorMath.cpp:36
# 4,3,28,64
# 4,3,64,32
# [28,64] @ [64,32] => [28,32]
torch.matmul(a,b).shape
torch.Size([4, 3, 28, 32])
# 4,3,28,64
# 4,1,64,32
# 4,1,64,32 => broadingcast:4,3,64,32
b=torch.rand(4,1,64,32)
torch.matmul(a,b).shape
torch.Size([4, 3, 28, 32])
# 4,3,28,64
# 4,64,32
b=torch.rand(4,64,32)
torch.matmul(a,b).shape
---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

<ipython-input-28-5feacf49e007> in <module>
      1 b=torch.rand(4,64,32)
----> 2 torch.matmul(a,b).shape


RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 1

Power 次方

a=torch.full([2,2],3.0)
print(a)
a.pow(2)
tensor([[3., 3.],
        [3., 3.]])





tensor([[9., 9.],
        [9., 9.]])
a**2
tensor([[9., 9.],
        [9., 9.]])
aa = a**2
aa.sqrt()
tensor([[3., 3.],
        [3., 3.]])
aa.rsqrt() # 开根号后求导
tensor([[0.3333, 0.3333],
        [0.3333, 0.3333]])
aa**(0.5)
tensor([[3., 3.],
        [3., 3.]])

exp log

a=torch.exp(torch.ones(2,2))
a
tensor([[2.7183, 2.7183],
        [2.7183, 2.7183]])
torch.log(a)
tensor([[1., 1.],
        [1., 1.]])

Approximation

▪ .floor() .ceil()

▪ .round()

▪ .trunc() .frac()

a=torch.tensor(3.14)
a
tensor(3.1400)
a.floor() # 向下取整
tensor(3.)
a.ceil() # 向上取整
tensor(4.)
a.round() # 四舍五入
tensor(3.)
a.frac() # 取小数部分
tensor(0.1400)
a.trunc() # 取整数部分
tensor(3.)
a=torch.tensor(3.499)
a.floor() # 向下取整
tensor(3.)
a.ceil()
tensor(4.)
a.trunc() # 取整数部分
tensor(3.)
a.frac() # 取小数部分
tensor(0.5000)
a.round() # 四舍五入
tensor(3.)
a=torch.tensor(3.5)
a
tensor(3.5000)
a.round() # 四舍五入
tensor(4.)

clamp

▪ gradient clipping

▪ (min)

▪ (min, max)

grad = torch.rand(2,3)*15
grad
tensor([[ 1.9749,  5.4683,  3.6834],
        [14.8391,  1.1953,  9.1021]])
grad.max()
tensor(14.8391)
grad.median()
tensor(3.6834)
grad.clamp(10) # 小于10的,替换为10
tensor([[10.0000, 10.0000, 10.0000],
        [14.8391, 10.0000, 10.0000]])
grad
tensor([[ 1.9749,  5.4683,  3.6834],
        [14.8391,  1.1953,  9.1021]])
grad.clamp(0, 10)  # 限定到(0, 10)之间
tensor([[ 1.9749,  5.4683,  3.6834],
        [10.0000,  1.1953,  9.1021]])
### PyTorch 中张量的数学运算 #### 基础概念 张量可以视为一个多维数组,在深度学习和科学计算中扮演着重要角色。张量支持多种数学运算,包括但不限于加法、减法、乘法、除法、内积、外积、张量积等[^2]。 #### 加法运算 对于两个形状相同的张量,可以通过简单的`+`操作符来执行逐元素相加的操作: ```python import torch tensor1 = torch.tensor([1, 2, 3, 4, 5]) tensor2 = torch.tensor([5, 4, 3, 2, 1]) print("加法结果:", tensor1 + tensor2) ``` 上述代码展示了如何创建两个一维张量并对其应用加法运算。 #### 减法运算 类似于加法,减法也可以通过 `-` 操作符实现,同样适用于同形张量之间的差分计算。 #### 乘法运算 有两种主要类型的乘法——按元素乘法(`*`) 和矩阵乘法 (`@`, `torch.matmul()` 或者 `torch.mm()`): - **按元素乘法** 当两个张量具有相同尺寸时,可以直接使用 `*` 来完成对应位置上的数值相乘: ```python result_elementwise_multiply = tensor1 * tensor2 ``` - **矩阵乘法** 如果需要做线性代数意义上的矩阵乘法,则应该采用 `@` 运算符或是调用相应的函数如 `torch.matmul()` : ```python matrix_a = torch.randn((4, 3)) matrix_b = torch.randn((3, 5)) product_matrix_mul = torch.matmul(matrix_a, matrix_b) # or using the '@' operator directly between tensors. direct_product = matrix_a @ matrix_b ``` 特别地,当处理批量数据(即三维及以上维度的数据集)时,还可以利用 `torch.bmm()` 执行批处理模式下的矩阵乘法[^3]. #### 广播机制简介 值得注意的是,即使在某些情况下张量并不严格满足维度匹配条件,Python 的 NumPy 库以及 PyTorch 都提供了所谓的“广播”功能,允许不同大小但兼容结构的张量之间进行有效的二元运算。不过这部分内容较为复杂,这里不做深入探讨[^4]. #### 完整实例展示 下面给出一段综合性的例子,涵盖了前面提到的各种基本运算方式: ```python import torch as t # 创建随机初始化的二维张量 t0 = t.randint(1, 10, size=(3, 4)) t1 = t.randint(1, 10, size=(3, 4)) print('原始张量:') print(f't0:\n{t0}\nt1:\n{t1}') # 计算两者之和 sum_result = t.add(t0, t1) print('\n加法后的结果:') print(sum_result) # 实现按位乘法 element_wise_multiplication = t.mul(t0, t1) print('\n按位乘法的结果:') print(element_wise_multiplication) # 构建适合于矩阵乘法的一对新张量 matrix_x = t.rand((2, 3), dtype=t.float64) matrix_y = t.rand((3, 4), dtype=t.float64) product_of_matrices = t.matmul(matrix_x, matrix_y) print('\n矩阵乘法的结果 (X * Y):') print(product_of_matrices) ``` 此段脚本不仅实现了基础的四则运算,还示范了更复杂的矩阵乘法规则及其具体应用场景.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值