Pytorch-数学运算
2024-08-28 14:10:40
引言
本篇介绍tensor的数学运算。
基本运算
- add/minus/multiply/divide
- matmul
- pow
- sqrt/rsqrt
- round
基础运算
- 可以使用 + - * / 推荐
- 也可以使用 torch.add, mul, sub, div
1 |
In[3]: a = torch.rand(3,4) |
torch.all()
判断每个位置的元素是否相同是否存在为0的元素
1
2
3
4In[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-wisetorch.mm(a,b)
只能计算2D 不推荐torch.matmul(a,b)
可以计算更高维度,落脚点依旧在行与列。 推荐@
是matmul 的重载形式
1 |
In[24]: a = 3*torch.ones(2,2) |
例子
线性层的计算 : 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 |
In[31]: x = torch.rand(4,784) |
神经网络 -> 矩阵运算 -> tensor flow
2维以上的tensor matmul
- 对于2维以上的matrix multiply ,
torch.mm(a,b)
就不行了。 - 运算规则:只取最后的两维做矩阵乘法
- 对于 [b, c, h, w] 来说,b,c 是不变的,图片的大小在改变;并且也并行的计算出了b,c。也就是支持多个矩阵并行相乘。
- 对于不同的size,如果符合broadcast,先执行broadcast,在进行矩阵相乘。
1 |
In[3]: a = torch.rand(4,3,28,64) |
power
- pow(a, n) a的n次方
**
也表示次方(可以是2,0.5,0.25,3) 推荐- sqrt() 表示 square root 平方根
- rsqrt() 表示平方根的倒数
1 |
In[11]: a = torch.full([2,2],3) |
Exp log
- exp(n) 表示:e的n次方
- log(a) 表示:ln(a)
- log2() 、 log10()
1 |
In[18]: a = torch.exp(torch.ones(2,2)) |
Approximation
近似相关1
- floor、ceil 向下取整、向上取整
- round 4舍5入
- trunc、frac 裁剪
1 |
In[24]: a = torch.tensor(3.14) |
clamp
近似相关2 (用的更多一些)
- gradient clipping 梯度裁剪
- (min) 小于min的都变为某某值
- (min, max) 不在这个区间的都变为某某值
- 梯度爆炸:一般来说,当梯度达到100左右的时候,就已经很大了,正常在10左右,通过打印梯度的模来查看
w.grad.norm(2)
- 对于w的限制叫做weight clipping,对于weight gradient clipping称为 gradient clipping。
1 |
In[30]: grad = torch.rand(2,3)*15 |
最新文章
- tomcat热部署
- jquery ajax GET POST 跨域请求实现
- Android平台调用WebService详解
- 为在MyEclipse中配置Tomcat服务器郁闷的朋友们解决郁闷
- SQL server 变量if,while,存储过程
- zabbix 参数说明
- plsql找外键约束关联的表的方法
- MVC 路由设置伪静态
- Class.jsp
- org.elasticsearch.client.transport.NoNodeAvailableException
- linux拷贝多个目录下的文件到同一个目录
- Javaweb学习笔记——(十二)——————JSP指令:page指令、include指令、taglib指令,JavaBean,内省,EL表达式
- 小学生都看得懂的C语言入门(5): 指针
- CH #46A - 磁力块 - [分块]
- C# 网络编程之webBrowser获取网页url和下载网页中图片
- 如何通过python代码解压zip包
- hdu1866 A + B forever!(面积并)题解
- 【JXOI2018】排序问题 贪心
- Kubernetes Deloyment实现滚动更新
- python orm字段解析
热门文章
- Mybatis 中的<;![CDATA[ ]]>;浅析
- Linux 设置服务开机启动
- HDU 6299
- JSONP跨域的script标签请求为什么不受同源策略的限制?
- JavaScript img标签自带的onload和onerror函数
- Mysql分区实战
- 牛客多校第五场 F take 期望转化成单独事件概率(模板) 树状数组
- codeforces 27 E. Number With The Given Amount Of Divisors(数论+dfs)
- hdu 1540 Tunnel Warfare(线段树)
- 【Offer】[19] 【字符串匹配】