引言

本篇介绍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. Spark基本函数学习

    package cn.itcast.spark.czh import org.apache.spark.{SparkConf, SparkContext} object TestFun { def m ...

  2. 【Leetcode】【简单】【217. 存在重复元素】【JavaScript】

    题目描述 217. 存在重复元素 给定一个整数数组,判断是否存在重复元素. 如果任何值在数组中出现至少两次,函数返回 true.如果数组中每个元素都不相同,则返回 false. 示例 1: 输入: [ ...

  3. 一位996、CRUD开发者的一天

    记一笔流水账 今天我打算记一笔流水账,主要记录我的一天中干的事情,并思考效率低下的原因,同时分析一些可用的解决方案. 清早·开始做计划 早上六点四十,被梦想唤醒,然后看一会书,吃早餐,送娃上学. 九点 ...

  4. 为什么有了Compose和Swarm,还会有Kubernetes的出现?

    一.k8s设计思想更先进 k8s的主要设置思想,是从更宏观的角度,以统一的方式来定义任务之间的各种关系 1.k8s的核心功能图 2.k8s的全局架构图 kube-apiserver:API服务 Kub ...

  5. STL 中priority_queue小结

    (1)为了运用priority_queue,你必须包含头文件<queue>:#include<queue>    (2)在头文件中priority_queue定义如下: nam ...

  6. Gym - 101667H - Rock Paper Scissors FFT 求区间相同个数

    Gym - 101667H:https://vjudge.net/problem/Gym-101667H 参考:https://blog.csdn.net/weixin_37517391/articl ...

  7. POJ 3164 Command Network 最小树形图 朱刘算法

    =============== 分割线之下摘自Sasuke_SCUT的blog============= 最 小树形图,就是给有向带权图中指定一个特殊的点root,求一棵以root为根的有向生成树T, ...

  8. codeforces 766 D. Mahmoud and a Dictionary(种类并查集+stl)

    题目链接:http://codeforces.com/contest/766/problem/D 题意:给你n个单词,m个关系(两个单词是反义词还是同义词),然后问你所给的关系里面有没有错的,最后再给 ...

  9. Python 之父的解析器系列之五:左递归 PEG 语法

    原题 | Left-recursive PEG grammars 作者 | Guido van Rossum(Python之父) 译者 | 豌豆花下猫("Python猫"公众号作者 ...

  10. Pytorch读取,加载图像数据(一)

    在学习Pytorch的时候,先学会如何正确创建或者加载数据,至关重要. 有了数据,很多函数,操作的效果就变得很直观. 本文主要用其他库读取图像文件(学会这个,你就可以在之后的学习中,将一些效果直观化) ...