pytorch基本数学运算 加法 减法 乘法 除法 指数 对数 绝对值

welcome to my blog

加法

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
b = torch.Tensor(np.arange(6).reshape((2,3)))
'''
b的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
res = torch.add(a,b)
print(res)
'''
结果
tensor([[ 0.,  2.,  4.],
        [ 6.,  8., 10.]])
'''

减法

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
b = torch.Tensor(np.random.randint(0,9,size=(2,3)))
'''
b的值
tensor([[4., 0., 5.],
        [6., 8., 4.]])
'''
res = torch.sub(a,b)
print(res)
'''
结果
tensor([[-4.,  1., -3.],
        [-3., -4.,  1.]])
'''

乘法

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
b = torch.Tensor(np.arange(6).reshape((2,3)))
'''
b的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
res = torch.mul(a, b)
print(res)
'''
tensor([[ 0.,  1.,  4.],
        [ 9., 16., 25.]])
'''

除法

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
b = torch.Tensor(np.random.randint(0,9,size=(2,3)))
'''
b的值
tensor([[4., 0., 5.],
        [6., 8., 4.]])
'''
res = torch.div(a,b)
print(res)
'''
结果, 注意到: 除数为0时的结果是inf, 并没有报错
tensor([[0.0000,    inf, 0.4000],
        [0.5000, 0.5000, 1.2500]])
'''

e为底的指数

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
# 底为e的指数
res = torch.exp(a)
print(res)
'''
tensor([[  1.0000,   2.7183,   7.3891],
        [ 20.0855,  54.5981, 148.4132]])
'''

n次方, n次幂

a = torch.randint(0,9,(1,))
'''
a的值
tensor([2])
'''
b = torch.randint(0,9,(1,))
'''
b的值
tensor([5])
'''
#求a的b次方
res = torch.pow(input=a,exponent=b)
print(res)
'''
tensor([32])
'''

对数

a = torch.Tensor(np.arange(6).reshape((2,3)))
'''
a的值
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
# 计算以e为底的对数
res = torch.log(a)
print(res)
'''
tensor([[  -inf, 0.0000, 0.6931],
        [1.0986, 1.3863, 1.6094]])
'''
# 计算以2为底的对数
res = torch.log2(a)
print(res)
'''
tensor([[  -inf, 0.0000, 1.0000],
        [1.5850, 2.0000, 2.3219]])
'''
# 计算以10为底的对数
res = torch.log10(a)
print(res)
'''
tensor([[  -inf, 0.0000, 0.3010],
        [0.4771, 0.6021, 0.6990]])
'''
# 计算以e为底, a+1的对数
res = torch.log1p(a)
print(res)
'''
tensor([[0.0000, 0.6931, 1.0986],
        [1.3863, 1.6094, 1.7918]])
'''

绝对值

a = torch.randint(-10,-1,(1,))
'''
a的值
tensor([-10])
'''

res = torch.abs(input=aaa)
print(res)
'''
tensor([10])
'''
发布了489 篇原创文章 · 获赞 101 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/103800012