引言

本篇介绍tensor的数学运算。

基本运算

  • add/minus/multiply/divide
  • matmul
  • pow
  • sqrt/rsqrt
  • round

基础运算

  • 可以使用 + - * / 推荐
  • 也可以使用 torch.add, mul, sub, div
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In[3]: a = torch.rand(3,4)
In[4]: b = torch.rand(4) # 使用broadcast
In[5]: a+b
Out[5]:
tensor([[0.9463, 1.3325, 1.0427, 1.3508],
[1.8552, 0.5614, 0.8546, 1.2186],
[1.4794, 1.3745, 0.7024, 1.1688]])
In[6]: torch.add(a,b)
Out[6]:
tensor([[0.9463, 1.3325, 1.0427, 1.3508],
[1.8552, 0.5614, 0.8546, 1.2186],
[1.4794, 1.3745, 0.7024, 1.1688]])
In[8]: torch.all(torch.eq((a-b),torch.sub(a,b)))
Out[8]: tensor(1, dtype=torch.uint8)
In[9]: torch.all(torch.eq((a*b),torch.mul(a,b)))
Out[9]: tensor(1, dtype=torch.uint8)
In[10]: torch.all(torch.eq((a/b),torch.div(a,b)))
Out[10]: tensor(1, dtype=torch.uint8)
  • torch.all() 判断每个位置的元素是否相同

    是否存在为0的元素

    1
    2
    3
    4
    In[21]: torch.all(torch.ByteTensor([1,1,1,1]))
    Out[21]: tensor(1, dtype=torch.uint8)
    In[22]: torch.all(torch.ByteTensor([1,1,1,0]))
    Out[22]: tensor(0, dtype=torch.uint8)

matmul

  • matmul 表示 matrix mul
  • * 表示的是element-wise
  • torch.mm(a,b) 只能计算2D 不推荐
  • torch.matmul(a,b) 可以计算更高维度,落脚点依旧在行与列。 推荐
  • @ 是matmul 的重载形式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In[24]: a = 3*torch.ones(2,2)
In[25]: a
Out[25]:
tensor([[3., 3.],
[3., 3.]])
In[26]: b = torch.ones(2,2)
In[27]: torch.mm(a,b)
Out[27]:
tensor([[6., 6.],
[6., 6.]])
In[28]: torch.matmul(a,b)
Out[28]:
tensor([[6., 6.],
[6., 6.]])
In[29]: [email protected]
Out[29]:
tensor([[6., 6.],
[6., 6.]])

例子

线性层的计算 : x @ w.t() + b

  • x是4张照片且已经打平了 (4, 784)
  • 我们希望 (4, 784) —> (4, 512)
  • 这样的话w因该是 (784, 512)
  • 但由于pytorch默认 第一个维度是 channel-out(目标), 第二个维度是 channel-in (输入) , 所以需要用一个转置

note:.t() 只适合2D,高维用transpose

1
2
3
4
In[31]: x = torch.rand(4,784)
In[32]: w = torch.rand(512,784)
In[33]: ([email protected]()).shape
Out[33]: torch.Size([4, 512])

神经网络 -> 矩阵运算 -> tensor flow

2维以上的tensor matmul

  • 对于2维以上的matrix multiply , torch.mm(a,b)就不行了。
  • 运算规则:只取最后的两维做矩阵乘法
  • 对于 [b, c, h, w] 来说,b,c 是不变的,图片的大小在改变;并且也并行的计算出了b,c。也就是支持多个矩阵并行相乘。
  • 对于不同的size,如果符合broadcast,先执行broadcast,在进行矩阵相乘。
1
2
3
4
5
6
7
8
9
10
11
12
In[3]: a = torch.rand(4,3,28,64)
In[4]: b = torch.rand(4,3,64,32)
In[5]: torch.mm(a,b).shape
RuntimeError: matrices expected, got 4D, 4D tensors at ..\aten\src\TH/generic/THTensorMath.cpp:956
In[6]: torch.matmul(a,b).shape
Out[6]: torch.Size([4, 3, 28, 32])
In[7]: b = torch.rand(4,1,64,32)
In[8]: torch.matmul(a,b).shape # 进行了broadcast
Out[8]: torch.Size([4, 3, 28, 32])
In[9]: b = torch.rand(4,64,32)
In[10]: torch.matmul(a,b).shape
RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 1

power

  • pow(a, n) a的n次方
  • ** 也表示次方(可以是2,0.5,0.25,3) 推荐
  • sqrt() 表示 square root 平方根
  • rsqrt() 表示平方根的倒数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
In[11]: a = torch.full([2,2],3)
In[12]: a.pow(2)
Out[12]:
tensor([[9., 9.],
[9., 9.]])
In[13]: a**2
Out[13]:
tensor([[9., 9.],
[9., 9.]])
In[14]: aa = a**2
In[15]: aa.sqrt()
Out[15]:
tensor([[3., 3.],
[3., 3.]])
In[16]: aa.rsqrt()
Out[16]:
tensor([[0.3333, 0.3333],
[0.3333, 0.3333]])
In[17]: aa**(0.5)
Out[17]:
tensor([[3., 3.],
[3., 3.]])

Exp log

  • exp(n) 表示:e的n次方
  • log(a) 表示:ln(a)
  • log2() 、 log10()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In[18]: a = torch.exp(torch.ones(2,2))
In[19]: a
Out[19]:
tensor([[2.7183, 2.7183],
[2.7183, 2.7183]])
In[20]: torch.log(a)
Out[20]:
tensor([[1., 1.],
[1., 1.]])
In[22]: torch.log2(a)
Out[22]:
tensor([[1.4427, 1.4427],
[1.4427, 1.4427]])
In[23]: torch.log10(a)
Out[23]:
tensor([[0.4343, 0.4343],
[0.4343, 0.4343]])

Approximation

近似相关1

  • floor、ceil 向下取整、向上取整
  • round 4舍5入
  • trunc、frac 裁剪
1
2
3
4
5
6
7
8
9
In[24]: a = torch.tensor(3.14)
In[25]: a.floor(),a.ceil(),a.trunc(),a.frac()
Out[25]: (tensor(3.), tensor(4.), tensor(3.), tensor(0.1400))
In[26]: a = torch.tensor(3.499)
In[27]: a.round()
Out[27]: tensor(3.)
In[28]: a = torch.tensor(3.5)
In[29]: a.round()
Out[29]: tensor(4.)

clamp

近似相关2 (用的更多一些)

  • gradient clipping 梯度裁剪
  • (min) 小于min的都变为某某值
  • (min, max) 不在这个区间的都变为某某值
  • 梯度爆炸:一般来说,当梯度达到100左右的时候,就已经很大了,正常在10左右,通过打印梯度的模来查看 w.grad.norm(2)
  • 对于w的限制叫做weight clipping,对于weight gradient clipping称为 gradient clipping。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
In[30]: grad = torch.rand(2,3)*15
In[31]: grad.max()
Out[31]: tensor(10.6977)
In[32]: grad.clamp(10)
Out[32]:
tensor([[10.0000, 10.6977, 10.0000],
[10.0000, 10.0000, 10.0000]])
In[33]: grad
Out[33]:
tensor([[ 6.7738, 10.6977, 4.4314],
[ 7.8088, 4.8236, 3.6213]])
In[34]: grad.clamp(0,10)
Out[34]:
tensor([[ 6.7738, 10.0000, 4.4314],
[ 7.8088, 4.8236, 3.6213]])

Pytorch-数学运算的更多相关文章

  1. pytorch数学运算与统计属性入门(非常易懂)

    pytorch数学运算与统计属性入门1.Broadcasting (维度)自动扩展,具有以下两个重要特征:(1)expand (2)without copying data重点的核心实现功能是:(1) ...

  2. Java学习笔记 06 数字格式化及数学运算

    一.数字格式化 DecimalFormat类 >>DecimalFormat是NumberFormat的子类,用于格式化十进制数,可以将一些数字格式化为整数.浮点数.百分数等.通过使用该类 ...

  3. 从零开始学习Node.js例子四 多页面实现数学运算 续二(client端和server端)

    1.server端 支持数学运算的服务器,服务器的返回结果用json对象表示. math-server.js //通过监听3000端口使其作为Math Wizard的后台程序 var math = r ...

  4. Linux shell 变量 数学 运算

    Abstract : 1)  Linux shell 中使用 let , [ ] ,(( )) 三种运算符操作 shell 变量进行简单的基本运算: 2)Linux shell 中使用 expr 与 ...

  5. 认真学习shell的第一天-数学运算

    shell中的数学运算有三种方式: (1)let,用let的时候,变量名称前不用添加$ (2)[],[]中变量可使用也可不使用$ (3)(())变量名之前必须添加$

  6. 6 让我们的C#程序开始做点数学运算

    请相信我你只需要懂得最基本的数学运算,就可以从事大多数的软件项目的开发工作.千万不要一提编程,就让数学把你吓跑了.大多数的程序开发人员从事的编程工作是应用系统的开发.这些系统的绝大多数功能,只需要最基 ...

  7. shell编程之数学运算

    shell数学运算支持整数运算的四种方法 1.let命令 no1=4; no2=5; let result=no1+no2 2.[]操作符 result=$[ no1 + no2] 3.(())操作符 ...

  8. 玩转变量、环境变量以及数学运算(shell)

    变量和环境变量    var=value  给变量赋值,输出语句:$ echo $var或者是$ echo ${var},记住中间有个空格 例如:name="coffee" age ...

  9. css3 calc():css简单的数学运算-加减乘除

    css3 calc():css简单的数学运算–加减乘除 多好的东西啊,不用js,一个css就解决了. .box{ border:1px solid #ddd; width:calc(100% - 10 ...

  10. Linux Shell 数学运算

    Linux Shell 数学运算 在Linux中直接使用数学运算符进行数学运算往往得不到我们想要的计算结果.要在Shell中进行数学运算,我们需要借助点小手段.目前,Linux Shell中进行数学运 ...

随机推荐

  1. SpringCould-------使用Hystrix 实现断路器进行服务容错保护

    消费: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or ...

  2. 关于python的特殊方法

    最近在阅读<流畅的python>这本书,在第一章中作者就提到了几个python中的特殊方法,代码入下: class FrenchDuck: ranks = [str(n) for n in ...

  3. mac系统chrome浏览器快捷键

    开发中谷歌浏览器常用快捷键: 开发者工具台快捷键:option+command+iconsole控制台快捷键:option+command+j 或者 option+command+c 1. 标签页和窗 ...

  4. 学习HTML之后的感受

    自从学习了HTML之后,感觉自己每天面对密密麻麻的代码,都有了一种密集恐惧症的感觉,作为一个计算机行业的小白,我十分渴望在计算机行业有所建树,以前计算机对我来说是一个神秘的领域.现在我正在努力进入这个 ...

  5. ROS中local costmap的原点坐标系

    local costmap是一个依赖于其他坐标系存在的坐标系统,它并不维护自己的坐标系,而是在另一个坐标系中设定坐标原点,然后记下自己的宽与高.它使用数据结构nav_msgs/OccupancyGri ...

  6. Keras(四)CNN 卷积神经网络 RNN 循环神经网络 原理及实例

    CNN 卷积神经网络 卷积 池化 https://www.cnblogs.com/peng8098/p/nlp_16.html 中有介绍 以数据集MNIST构建一个卷积神经网路 from keras. ...

  7. c#中的委托01

    delegate 是表示对具有特定参数列表和返回类型的方法的引用的类型. 在实例化委托时,你可以将其实例与任何具有兼容签名和返回类型的方法相关联. 你可以通过委托实例调用方法. 委托用于将方法作为参数 ...

  8. iOS Autoresizing Autolayout Size classes

    Autoresizing:出现最早,仅仅能够针对父控件做约束(注意:要关闭Autolayout&Size classes才能够看到Autoresizing) 代码对应: UIView.h中的a ...

  9. Scrum的三个仪式:Sprint规划会,Scrum每日站会,Sprint评审会

    转自:http://blog.sina.com.cn/s/blog_6997f01501010m21.html Sprint Planning Meeting(Sprint规划会) 根据Product ...

  10. 洛谷- P1306 斐波那契公约数 - 矩阵快速幂 斐波那契性质

    P1306 斐波那契公约数:https://www.luogu.org/problemnew/show/P1306 这道题目就是求第n项和第m项的斐波那契数字,然后让这两个数求GCD,输出答案的后8位 ...