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

无人久伴 提交于 2020-01-02 12:35:08

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]])
'''

指数

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

对数

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]])
'''
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!