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

加法

import torch
import numpy as np

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

减法

print('# 减法')
a = torch.Tensor(np.arange(6).reshape(2, 3))
b = torch.Tensor(np.random.randint(0, 9, size=(2, 3)))
res = torch.sub(a, b)
print(a)
'''
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
print(b)
'''
tensor([[0., 1., 5.],
        [3., 1., 3.]])
'''
print(res)
'''
tensor([[ 0.,  0., -3.],
        [ 0.,  3.,  2.]])
'''

乘法

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

除法

rint('# 除法')
a = torch.Tensor(np.arange(6).reshape(2, 3))
b = torch.Tensor(np.random.randint(0, 9, size=(2, 3)))
res = torch.div(a, b)
print(a)
'''
tensor([[0., 1., 2.],
        [3., 4., 5.]])
'''
print(b)
'''
tensor([[8., 6., 8.],
        [8., 0., 4.]])
'''
print(res)
# 当除数为0时,结果为inf
'''
tensor([[0.0000, 0.1667, 0.2500],
        [0.3750,    inf, 1.2500]])
'''

指数

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

print('# n次幂,n次方')
a = torch.randint(0, 9, (2, 3))
b = torch.randint(0, 9, (2, 3))
res = torch.pow(input=a, exponent=b)
print(a)
'''
tensor([[1, 5, 4],
        [8, 6, 0]])
'''
print(b)
'''
tensor([[8, 8, 3],
        [8, 5, 8]])
'''
print(res)
'''
tensor([[       1,   390625,       64],
        [16777216,     7776,        0]])
'''

对数

print('# 对数')
a = torch.Tensor(np.arange(6).reshape(2, 3))
print(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]])
'''

绝对值

print('# 绝对值')
a = torch.randint(-10, -1, (2, 3))
print(a)
'''
tensor([[-5, -8, -3],
        [-6, -9, -5]])
'''
res = torch.abs(a)
print(res)
'''
tensor([[5, 8, 3],
        [6, 9, 5]])
'''

猜你喜欢

转载自blog.csdn.net/qq_40507857/article/details/123105683