pytorch基本运算:加减乘除、对数幂次等

时间:2020-06-03 23:33:06   收藏:0   阅读:338

1、加减乘除

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)    

2、矩阵相乘

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

3、幂次计算

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

4、自然底数与对数

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

5、近似值

6、限幅

原文:https://www.cnblogs.com/jaysonteng/p/13040596.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!