Tensor的数学运算

PyTorch数学运算详解
部署运行你感兴趣的模型镜像

前言:

本文讲解有关Tensor的基础数学运算

一、基础运算

1、相关函数

  1. 加法:a + btorch.add(a,b)
  2. 减法:a - btorch.sub(a,b)
  3. 乘法:a * btorch.mul(a,b)
  4. 除法:a / btorch.div(a,b)

2、代码实例

a = torch.rand(3,4)
b = torch.rand(4)

print(torch.all(torch.eq(a-b,torch.sub(a,b))))
print(torch.all(torch.eq(a+b,torch.add(a,b))))
print(torch.all(torch.eq(a*b,torch.mul(a,b))))
print(torch.all(torch.eq(a/b,torch.div(a,b))))
# 输出是: tensor(True)

二、矩阵运算

1、相关函数

  1. torch.mm(a,b):矩阵乘法,适用于dim=2
  2. torch.matmul(a,b):矩阵乘法,适用范围广泛,并支持Broadcasting机制(传送门)
  3. a @ b:矩阵乘法,与torch.matmul(a,b)用法相同

2、代码实例

  1. dim=2的例子
a = torch.FloatTensor([[3,3],[3,3]])
b = torch.ones(2,2)
c = a * b # element_wise,这里是.*,不是matrix乘法
print(c)
# tensor([[3., 3.],
#        [3., 3.]])

c = torch.mm(a,b) # 只适用于dim=2
print(c)
# tensor([[6., 6.],
#        [6., 6.]])

c = torch.matmul(a,b)
print(c)
# tensor([[6., 6.],
#        [6., 6.]])

c = a @ b
print(c)
# tensor([[6., 6.],
#        [6., 6.]])
  1. 在神经网络中完成降维过程
# 神经网络中完成将维度的过程 [4,784] => [4,512]
a = torch.rand(4,784)
x = torch.rand(4,784)
w = torch.rand(512,784)
ans = x @ w.t() #.t()只适合2d
print(ans.shape)
  1. 高dim的matmul实例
a = torch.rand(4,3,28,64)
b = torch.rand(4,3,64,32)
c = torch.matmul(a,b) # 前两维度不变,后两维度做matmul 
print(c.shape)
# out : torch.Size([4, 3, 28, 32])

b = torch.rand(4,1,64,32) # 后两维度做matmul,前两维度做Broadcasting机制b变换成[4,3]
c = torch.matmul(a,b) 
print(c.shape)
# out: torch.Size([4, 3, 28, 32])

三、power函数

1、相关函数

  1. a.pow(x):完成 a x a^{x} ax运算
  2. a ** x:完成 a x a^{x} ax运算
  3. a.sqrt():完成 a 0.5 a^{0.5} a0.5运算
  4. `a.rsqrt()``:完成平方根导数运算

2、代码实例

a = torch.full([2,2],3)
#  tensor([[3., 3.],
#         [3., 3.]])

b = a.pow(2)
print(b)
# tensor([[9., 9.],
#         [9., 9.]])

b = a ** 2
print(b)
# tensor([[9., 9.],
#         [9., 9.]])

c = b.sqrt() # 平方根
print(c)
# tensor([[3., 3.],
#        [3., 3.]])

c = b.rsqrt() # 平方根导数
print(c)
# tensor([[0.3333, 0.3333],
#         [0.3333, 0.3333]])

c = b ** (0.5) # sqrt
print(c)
# tensor([[3., 3.],
#        [3., 3.]])

四、exp函数与log函数

1、相关函数

  1. torch.exp(tensor):对于每一个数,都取 e x e^x ex
  2. torch.log(tensor):对于每一个数,都取 l o g e x log_ex logex,该函数默认e为底,若想以其他为底,可以使用torch.log2等,或者使用换底公式

2、代码实例

a = torch.exp(torch.ones(2,2)) # e^1
# tensor([[2.7183, 2.7183],
#        [2.7183, 2.7183]])

b = torch.log(a)
print(b)
# tensor([[1., 1.],
#         [1., 1.]])

五、近似函数

1、相关函数

  1. a.floor():向下取整
  2. a.ceil():向上取整
  3. a.trunc():取整数部分
  4. a.frac():取小数部分
  5. a.round():四舍五入

2、代码实例

a = torch.tensor(3.1415)
print(a.floor()) # 向下取整 tensor(3.)
print(a.ceil()) # 向上取整 tensor(4.)
print(a.trunc()) # 取整数部分 tensor(3.)
print(a.frac()) # 取小数部分 tensor(0.1415)
# --------------------------------------------
a = torch.tensor(3.499)
print(a.round()) # tensor(3.)
a = torch.tensor(3.5)
print(a.round()) # tensor(4.)

六、clamp函数

1、相关函数

  1. a.max():找到最大的数
  2. a.median():找到中位数
  3. a.clamp(min,max):将范围设置为[min,max]之间,不在其范围内的,置成最大值或最小值。若只输入一个数,则代表输入的是min,max取正无穷

2、代码实例

grad = torch.rand(2,3)*15
print(grad)
# tensor([[ 1.3345, 10.6758, 12.4728],
#        [ 7.3111,  0.3316,  8.4921]])

print(grad.max())
# tensor(12.4728)

print(grad.median())
# tensor(7.3111)

print(grad.clamp(10)) # 小于10置为10
# tensor([[10.0000, 10.6758, 12.4728],
#        [10.0000, 10.0000, 10.0000]])

print(grad.clamp(0,10)) # 限制在[0,10]
# tensor([[ 1.3345, 10.0000, 10.0000],
#        [ 7.3111,  0.3316,  8.4921]])

您可能感兴趣的与本文相关的镜像

PyTorch 2.5

PyTorch 2.5

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

### PyTorch Tensor 支持的数学运算 #### 加法操作 Tensor 对象之间可以通过 `+` 运算符执行加法,也可以利用 `torch.add()` 函数完成同样的功能。这允许两个张量相加以获得一个新的张量作为结果。 ```python import torch a = torch.tensor([1., 2., 3.]) b = torch.tensor([4., 5., 6.]) c_add_operator = a + b c_torch_add_function = torch.add(a, b) print(c_add_operator) # 输出 tensor([5., 7., 9.]) print(c_torch_add_function) # 输出 tensor([5., 7., 9.]) ``` #### 减法操作 类似于加法的操作方式,减法则可通过 `-` 或者 `torch.sub()` 来实现。 ```python d_sub_operator = a - b d_torch_sub_function = torch.sub(a, b) print(d_sub_operator) # 输出 tensor([-3., -3., -3.]) print(d_torch_sub_function) # 输出 tensor([-3., -3., -3.])[^2] ``` #### 乘法操作 对于元素级别的乘法,既可以采用 `*` 符号也能借助于 `torch.mul()` 方法;而矩阵之间的乘法则应使用 `@` 或者 `torch.matmul()` 函数来进行。 ```python e_mul_elementwise_operator = a * b f_matmul_matrix_multiplication = a @ b.T print(e_mul_elementwise_operator) # 输出 tensor([ 4., 10., 18.]) print(f_matmul_matrix_multiplication)# 输出 tensor(32.) ``` #### 除法操作 同样地,除法既可以用 `/` 实现按元素划分,也可用 `torch.div()` 达成相同目的。 ```python g_div_elementwise_operator = a / b h_torch_div_function = torch.div(a, b) print(g_div_elementwise_operator) # 输出 tensor([0.2500, 0.4000, 0.5000]) print(h_torch_div_function) # 输出 tensor([0.2500, 0.4000, 0.5000]) ``` #### 幂次方和其他特殊函数 除了上述四则运算外,还有诸如幂(`pow`)、指数(`exp`)、对数(`log`)等更多高级数学运算可供选择。 ```python i_pow_example = torch.pow(a, 2) j_exp_example = torch.exp(b) k_log_example = torch.log(torch.abs(b)) print(i_pow_example) # 输出 tensor([1., 4., 9.]) print(j_exp_example) # e 的 b 次方的结果 print(k_log_example) # 绝对值后的自然对数 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值