引言

本篇介绍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. shiro 定义realm

    public class UserRealm extends AuthorizingRealm { private UserService userService = new UserServiceI ...

  2. NMS的python实现

    https://blog.csdn.net/a1103688841/article/details/89711120

  3. python+jinja2实现接口数据批量生成工具

    在做接口测试的时候,我们经常会遇到一种情况就是要对接口的参数进行各种可能的校验,手动修改很麻烦,尤其是那些接口参数有几十个甚至更多的,有没有一种方法可以批量的对指定参数做生成处理呢. 答案是肯定的! ...

  4. python 18 re模块

    目录 re 模块 1. 正则表达式 2. 匹配模式 3. 常用方法 re 模块 1. 正则表达式 \w 匹配字母(包含中文)或数字或下划线 \W 匹配非字母(包含中文)或数字或下划线 \s 匹配任意的 ...

  5. 手写迷你SpringMVC框架

    前言 学习如何使用Spring,SpringMVC是很快的,但是在往后使用的过程中难免会想探究一下框架背后的原理是什么,本文将通过讲解如何手写一个简单版的springMVC框架,直接从代码上看框架中请 ...

  6. excel表格导出之后身份证号列变成了科学计数法

    excel表格导出之后身份证号列变成了科学计数法 解决:写sql查询出所有数据,并在身份证列添加字符,然后导出,将要复制的excel表格设置单元格格式问文本类型,然后复制粘贴,再把加入的字符删除,搞定 ...

  7. 基于springboot的websocket聊天室

    WebSocket入门 1.概述 1.1 Http #http简介 HTTP是一个应用层协议,无状态的,端口号为80.主要的版本有1.0/1.1/2.0. #http1.0/1.1/2.0 1.HTT ...

  8. SpringMVC整合Apache Shiro

    关于什么是Shiro,可以查看这篇文章http://www.cnblogs.com/Laymen/articles/6117751.html 一.添加maven依赖 <dependency> ...

  9. CodeForces - 938D-Buy a Ticket+最短路

    Buy a Ticket 题意:有n个点和m条路(都收费),n个点在开演唱会,门票不同,对于生活在n个点的小伙伴,要求计算出每个小伙伴为了看一场演唱会要花费的最小价格: 思路: 这道题我一开始觉得要对 ...

  10. codeforces 830 B. Cards Sorting(线段树)

    题目链接:http://codeforces.com/contest/830/problem/B 题解:其实这题就是求当前大小的数到下一个大小的数直接有多少个数,这时候可以利用数据结构来查询它们之间有 ...