Pytorch跟Python一样都是一种编程语言,只不过Pytorch可以在GPU中进行计算。简单理解的话,就是这个区别吧。至于如何学习Pytorch,个人 觉得完全可以类比,Python两者语法跟用法没有太大差异。再者,为什么学习Pytorch基本计算,而不是用Python基本计算代替再转成tensor格式。个人在代码实现中的体会是:太麻烦,因为Pytorch默认创建变量的类型是float32,使用Python的数据类型如array是float64,如果进行tensor的转换后在计算会报错,变量类型不一致。而且如果自定义loss函数,在loss中的计算也必须使用Pytorch自带的计算方式,这算是个开场白了。
一、加减乘除
#加减乘除
a + b = torch.add(a, b)
a - b = torch.sub(a, b)
a * b = torch.mul(a, b)
a / b = torch.div(a, b)
#实操
import torch
a = torch.rand(3, 4)
b = torch.rand(4)
a
# 输出:
tensor([[0.6232, 0.5066, 0.8479, 0.6049],
[0.3548, 0.4675, 0.7123, 0.5700],
[0.8737, 0.5115, 0.2106, 0.5849]])
b
# 输出:
tensor([0.3309, 0.3712, 0.0982, 0.2331])
# 相加
# b会被广播
a + b
# 输出:
tensor([[0.9541, 0.8778, 0.9461, 0.8380],
[0.6857, 0.8387, 0.8105, 0.8030],
[1.2046, 0.8827, 0.3088, 0.8179]])
# 等价于上面相加
torch.add(a, b)
# 输出:
tensor([[0.9541, 0.8778, 0.9461, 0.8380],
[0.6857, 0.8387, 0.8105, 0.8030],
[1.2046, 0.8827, 0.3088, 0.8179]])
# 比较两个是否相等
torch.all(torch.eq(a + b, torch.add(a, b)))
# 输出:
tensor(True)
二、矩阵相乘
torch.mm(a, b) # 此方法只适用于2维
torch.matmul(a, b)
a @ b = torch.matmul(a, b) # 推荐使用此方法
#实操
a = torch.full((2, 2), 3)
a
# 输出
tensor([[3., 3.],
[3., 3.]])
b = torch.ones(2, 2)
b
# 输出
tensor([[1., 1.],
[1., 1.]])
torch.mm(a, b)
# 输出
tensor([[6., 6.],
[6., 6.]])
torch.matmul(a, b)
# 输出
tensor([[6., 6.],
[6., 6.]])
a @ b
# 输出
tensor([[6., 6.],
[6., 6.]])
三、幂次计算
pow, sqrt, rsqrt
a = torch.full([2, 2], 3)
a
# 输出
tensor([[3., 3.],
[3., 3.]])
a.pow(2)
# 输出
tensor([[9., 9.],
[9., 9.]])
aa = a ** 2
aa
# 输出
tensor([[9., 9.],
[9., 9.]])
# 平方根
aa.sqrt()
# 输出
tensor([[3., 3.],
[3., 3.]])
# 平方根
aa ** (0.5)
# 输出
tensor([[3., 3.],
[3., 3.]])
# 平方根
aa.pow(0.5)
# 输出
tensor([[3., 3.],
[3., 3.]])
# 平方根的倒数
aa.rsqrt()
# 输出
tensor([[0.3333, 0.3333],
[0.3333, 0.3333]])
tensor([[3., 3.],
[3., 3.]])
四、自然底数与对数
a = torch.ones(2, 2)
a
# 输出
tensor([[1., 1.],
[1., 1.]])
# 自认底数e
torch.exp(a)
# 输出
tensor([[2.7183, 2.7183],
[2.7183, 2.7183]])
# 对数
# 默认底数是e
# 可以更换为Log2、log10
torch.log(a)
# 输出
tensor([[0., 0.],
[0., 0.]])
五、近似值
a.floor() # 向下取整:floor,地板
a.ceil() # 向上取整:ceil,天花板
a.trunc() # 保留整数部分:truncate,截断
a.frac() # 保留小数部分:fraction,小数
a.round() # 四舍五入:round,大约
六、限幅
a.max() # 最大值
a.min() # 最小值
a.median() # 中位数
a.clamp(10) # 将最小值限定为10
a.clamp(0, 10) # 将数据限定在[0, 10],两边都是闭区间