• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# 【小白学PyTorch】10 pytorch常见运算详解

2周前 (09-14) 19次浏览

• 1 矩阵与标量
• 2 哈达玛积
• 3 矩阵乘法
• 4 幂与开方
• 5 对数运算
• 6 近似值运算
• 7 剪裁运算

## 1 矩阵与标量

``````import torch
a = torch.tensor([1,2])
print(a+1)
>>> tensor([2, 3])
``````

## 2 哈达玛积

``````a = torch.tensor([1,2])
b = torch.tensor([2,3])
print(a*b)
print(torch.mul(a,b))
>>> tensor([2, 6])
>>> tensor([2, 6])
``````

``````a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.])
print(a/b)
print(torch.div(a/b))
>>> tensor([0.5000, 0.6667])
>>> tensor([0.5000, 0.6667])
``````

## 3 矩阵乘法

• `torch.mm()`
• `torch.matmul()`
• `@`，这个需要记忆，不然遇到这个可能会挺蒙蔽的
``````a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.]).view(1,2)
print(torch.mm(a, b))
print(torch.matmul(a, b))
print(a @ b)
``````

``````tensor([[2., 3.],
[4., 6.]])
tensor([[2., 3.],
[4., 6.]])
tensor([[2., 3.],
[4., 6.]])
``````

``````a = torch.rand((1,2,64,32))
b = torch.rand((1,2,32,64))
print(torch.matmul(a, b).shape)
>>> torch.Size([1, 2, 64, 64])
``````

``````a = torch.rand((3,2,64,32))
b = torch.rand((1,2,32,64))
print(torch.matmul(a, b).shape)
>>> torch.Size([3, 2, 64, 64])
``````

## 4 幂与开方

``````print('幂运算')
a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.])
c1 = a ** b
c2 = torch.pow(a, b)
print(c1,c2)
>>> tensor([1., 8.]) tensor([1., 8.])
``````

## 5 对数运算

pytorch中log是以e自然数为底数的，然后log2和log10才是以2和10为底数的运算。

``````import numpy as np
print('对数运算')
a = torch.tensor([2,10,np.e])
print(torch.log(a))
print(torch.log2(a))
print(torch.log10(a))
>>> tensor([0.6931, 2.3026, 1.0000])
>>> tensor([1.0000, 3.3219, 1.4427])
>>> tensor([0.3010, 1.0000, 0.4343])
``````

## 6 近似值运算

• `.ceil()` 向上取整
• `.floor()`向下取整
• `.trunc()`取整数
• `.frac()`取小数
• `.round()`四舍五入
``````a = torch.tensor(1.2345)
print(a.ceil())
>>>tensor(2.)
print(a.floor())
>>> tensor(1.)
print(a.trunc())
>>> tensor(1.)
print(a.frac())
>>> tensor(0.2345)
print(a.round())
>>> tensor(1.)
``````

## 7 剪裁运算

``````a = torch.rand(5)
print(a)
print(a.clamp(0.3,0.7))
``````

``````tensor([0.5271, 0.6924, 0.9919, 0.0095, 0.0340])
tensor([0.5271, 0.6924, 0.7000, 0.3000, 0.3000])
``````