Tensor的数学运算

前言:

本文讲解有关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中的数学运算 #### 基本算术运算 PyTorch支持多种基本的算术运算,包括加减乘除以及幂次方根等特殊运算。对于两个相同尺寸的张量可以执行逐元素相加、相减、相乘和相除操作[^1]。 ```python import torch tensor_a = torch.tensor([2.0, 3.0]) tensor_b = torch.tensor([4.0, 5.0]) addition_result = tensor_a + tensor_b subtraction_result = tensor_a - tensor_b multiplication_result = tensor_a * tensor_b division_result = tensor_a / tensor_b power_result = torch.pow(tensor_a, 2) print(f'Addition Result: {addition_result}') print(f'Subtraction Result: {subtraction_result}') print(f'Multiplication Result: {multiplication_result}') print(f'Division Result: {division_result}') print(f'Power Result: {power_result}') # 幂运算示例 ``` #### 高级数学函数 除了简单的四则运算外,还提供了丰富的高级数学功能,比如三角函数(sin, cos)、双曲函数(tanh),以及其他常见的数值处理方法如指数exp()、自然对数log()[^5]。 ```python data = torch.tensor([0., math.pi/2, math.pi/4]) sine_values = torch.sin(data) cosine_values = torch.cos(data) hyperbolic_tangent_values = torch.tanh(data) print(f"Sine Values: {sine_values}") print(f"Cosine Values: {cosine_values}") print(f"Hyperbolic Tangent Values: {hyperbolic_tangent_values}") ``` #### 矩阵乘法 当涉及到线性代数领域内的计算时,`torch.mm()`用于常规矩阵乘法;而`torch.matmul()`或`@`符号可用于更广泛的场景下实现广播机制下的批量矩阵乘法[^4]。 ```python matrix_A = torch.randn(3, 4) matrix_B = torch.randn(4, 2) product_mm = torch.mm(matrix_A, matrix_B) product_matmul = torch.matmul(matrix_A, matrix_B) product_operator = matrix_A @ matrix_B assert (product_mm == product_matmul).all() assert (product_mm == product_operator).all() print(product_mm) ``` #### 统计聚合操作 为了方便数据分析工作流,在PyTorch里也内置了一些统计汇总的功能,像mean(), sum(), max(), min()等等,可以帮助快速获取整个张量或者指定维度上的统计数据. ```python random_tensor = torch.rand((3, 4)) sum_elements = random_tensor.sum(dim=0) # 对每一列求和 maximum_value_per_row = random_tensor.max(dim=1)[0] print(sum_elements) print(maximum_value_per_row) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值