引言

本篇介绍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. Freemarker提供了3种加载模板目录的方法

    Freemarker提供了3种加载模板目录的方法 原创 2016年08月24日 14:50:13 标签: freemarker / Configuration 8197 Freemarker提供了3种 ...

  2. (四十七)c#Winform自定义控件-树表格(treeGrid)

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  3. (五十)c#Winform自定义控件-滑块

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  4. Codeforces 1008D/1007B

    题意略. 思路: 由于这个长方体是可以翻转的,所以我们不必考虑小长方体3个维度的出处,反正3条边一定有长有短能分出大小. 现在我们来考虑A,B,C三个数字,如果它们3个产生的因子互不相同,分别产生了a ...

  5. 在.net core web 项目中操作MySql数据库(非ORM框架,原生sql语句方式)

    本案例通过MySql.Data和Dapper包执行原生sql,实现对数据库的操作. 操作步骤: 第1步:在MySql数据库中新建表User(使用Navicat For MySql工具) 建表语句: c ...

  6. CodeM资格赛 优惠券

    [编程|1000分] 优惠券 时间限制:1秒空间限制:32768K 题目描述 美团点评上有很多餐馆优惠券,用户可以在美团点评App上购买.每种优惠券有一个唯一的正整数编号.每个人可以拥有多张优惠券,但 ...

  7. Linux系统调用表(x86_64)

    内核版本 Linux 4.7 Note:64位系统中,不再使用int 0x80来进行系统调用,取而代之的是syscall指令 %rax System call %rdi %rsi %rdx %r10 ...

  8. javascript 多个异步处理解决方法

    JS异步处理真是一个让人头疼的东西,尤其是AJAX这个玩意.刚开始为了方便我会将jquery ajax 这个属性这样设置 async: false但是这样做问题很多,会让浏览器假死,好在ajax提供了 ...

  9. 【Offer】[64] 【求1+2+...+n】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 求1+2+...+n,要求不能使用乘除法.for. while if else. switch. case等关键字及条件判断语句( A? ...

  10. 009 Python基本图形绘制

    目录 一.概论 二.方法论 三.实践能力 一.概论 深入理解Python语言 实例2: Python蟒蛇绘制 模块1: turtle库的使用 turtle程序语法元素分析 二.方法论 Python语言 ...