版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sherpahu/article/details/95935845
文章目录
Tensor
运算
变换
torch.Tensor.transpose()&torch.Tensor.permute()
torch.cat() & torch.stack()
torch.squeeze()&torch.unsqueeze()
torch.Tensor.expand()&torch.Tensor.expand_as()
torch.contiguous()
torch.Tensor.view(*args)->Tensor
常用层
nn.Sequential()
nn.Linear()
nn.Conv2d()
归一化层
池化层
Dropout层
常用激活函数
常用损失函数
Tensor
运算
操作    功能
torch.abs    绝对值
torch.add    
torch.clamp    裁剪
torch.div    
torch.mul    逐元素求积
torch.pow    
torch.mm    矩阵乘法
torch.mv    矩阵向量乘法
变换
torch.Tensor.transpose()&torch.Tensor.permute()
transpose一次只能操作矩阵的两个维度,只接收两个维度的参数。

permute可以同时对多个维度进行操作

a=torch.rand(2,3,4)#torch.Size([2,3,4])
b=a.transpose(0,1)#torch.Size([3,2,4])

c=a.transpose(0,1).transpose(1,2)#torch.Size([3,4,2])
d=a.permute(1,2,0)#torch.Size([3,4,2])
1
2
3
4
5
torch.cat() & torch.stack()
cat是对数据沿着某一个维度对seq中的Tensor进行拼接,操作之后总维数不变,只在统一维度进行拼接。

torch.cat(seq, dim=0, out=None) → Tensor

参数:

seq (sequence of Tensors) - Python序列或相同类型的张量序列
dim (int, optional) - 沿着此维度连接张量
out (Tensor, optional) - 输出参数
除了在拼接的维度外,其余维度必须相等才能拼接。

a=torch.rand(2,3)
b=torch.rand(4,3)
c=torch.cat((a,b),axis=0)#torch.Size([6,3])
1
2
3
stack是在增加新的维度后进行“堆叠”,而不是直接拼接。会增加维度。

在对数据进行加载组合为一个batch时常常用到。

a=torch.rand([2,224,224])
b=torch.rand([3,224,224])
c=torch.stack((a,b),0)#torch.Size([2,3,224,224])
d=torch.stack((a,b),3)#torch.Size([3,224,224,2])
1
2
3
4
torch.squeeze()&torch.unsqueeze()
squeeze(dim_n)压缩,去掉元素数为1的dim_n的维度。

torch.squeeze(input, dim=None, out=None) → Tensor

参数:

input (Tensor) – 输入张量
dim (int, optional) – 如果给定,则只会在给定维度压缩
out (Tensor, optional) – 输出张量
unsqueeze(dim_n)增加dim_n维度,元素数目为1,与squeeze相反。

a=torch.rand(2,1,4)#torch.Size([2,1,4])
b=a.squeeze()#torch.Size([2,4]),去掉了元素个数为1的第二个维度
c=a.squeeze(1)#torch.Size([2,4]),同上
d=a.squeeze(2)#torch.Size([2,1,4]),第三个维度的元素个数不为1,不能去掉

e=a.unsqueeze(0)#torch.Size([1,2,1,4]),新增了第1个维度
1
2
3
4
5
6
torch.Tensor.expand()&torch.Tensor.expand_as()
torch.Tensor.expand(sizes) → Tensor

扩大张量,并且将张量复制使之变为对应size大小

x=torch.Tensor([[1],[2],[3]])#torch.Size([3,1])
x.expand(3,4)#torch.Size([3,4]),[[1,1,1,1],[2,2,2,2],[3,3,3,3]]
1
2
torch.Tensor.expand_as(size)

扩大张量,并且将张量变为对应Tensor的大小

a=torch.Tensor([[1],[2],[3]])
b=torch.Tensor([[4]])
c=b.expand_as(a)
#tensor([[4],[4],[4]])
1
2
3
4
torch.contiguous()
contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。 因为view需要tensor的内存是整块的。有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式。判断是否contiguous用torch.Tensor.is_contiguous()函数

x=torch.ones(10,10)
x.is_contiguous()  #True
x.transpose(0,1).is_contiguous()  #False
x.transpose(0, 1).contiguous().is_contiguous()  #True
1
2
3
4
因此,在调用view之前最好先contiguous一下,x.contiguous().view() 。

torch.Tensor.view(*args)->Tensor
参数:

args (torch.Size or int…) - 理想的指定尺寸
返回具有相同数据,但是形状与args所述相同的新的Tensor

a=torch.rand(4,4)#torch.Size([4,4])
b=x.view(16)#torch.Size([16])
1
2
常用层
nn.Sequential()
参数:若干其他层

torch.nn.Sequential 其实就是 Sequential 容器,该容器将一系列操作按先后顺序给包起
来,方便重复使用。将若干简单的层组合起来,方便结构显示与重用。

nn.Sequential(
    nn.Conv2d(in_dim,6,3,stride=1,padding=1),
    nn.ReLU(True),
    nn.MaxPool2d(2,2),
    nn.Conv2d(6,16,5,stride=1,padding=0),
    nn.ReLU(True),
    nn.MaxPool2d(2,2)
)
1
2
3
4
5
6
7
8
nn.Linear()
参数:输入维度,输出维度

nn.Linear(dim_in,dim_out)
1
y=xWT+b y=xW^{T}+by=xW 
T
 +b

作用:全连接

import torch

x = torch.randn(128, 20)  # 输入的维度是(128,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:\n ', m.weight.shape)
print('m.bias.shape:\n', m.bias.shape)
print('output.shape:\n', output.shape)

# ans = torch.mm(input,torch.t(m.weight))+m.bias 等价于下面的
ans = torch.mm(x, m.weight.t()) + m.bias#y=x*W^T+b,weight要转置
print('ans.shape:\n', ans.shape)

print(torch.equal(ans, output))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
m.weight.shape:
  torch.Size([30, 20])
m.bias.shape:
 torch.Size([30])
output.shape:
 torch.Size([128, 30])
ans.shape:
 torch.Size([128, 30])
True
1
2
3
4
5
6
7
8
9
nn.Linear()与nn.Conv1d()在kernel_size=1时等价,但是nn.Linear()启动更快

nn.Conv2d()
参数:in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True

输入大小、输出大小、卷积核个数groups、卷积核大小kernel_size、滑动步长stride和填充量padding

kernel_size, stride, padding, dilation 不但可以是一个单个的int——表示在高度和宽度使用这个相同的int作为参数

nn.Conv2d(6, 16, 5, stride=1, padding=0)
1
归一化层
nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True)
nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True)
nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True)
nn.InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False)
nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False)
nn.InstanceNorm3d(num_features, eps=1e-05, momentum=0.1, affine=False)
1
2
3
4
5
6
池化层
nn.MaxPl1d(knl_iz, tid=Nn, padding=0, dilatin=1, tn_indi=Fal, il_md=Fal)
nn.MaxPl2d(knl_iz, tid=Nn, padding=0, dilatin=1, tn_indi=Fal, il_md=Fal)
nn.MaxPl3d(knl_iz, tid=Nn, padding=0, dilatin=1, tn_indi=Fal, il_md=Fal)
nn.Maxnpl1d(knl_iz, tid=Nn, padding=0)
nn.Maxnpl2d(knl_iz, tid=Nn, padding=0)
nn.Maxnpl3d(knl_iz, tid=Nn, padding=0)
nn.AvgPl1d(knl_iz, tid=Nn, padding=0, il_md=Fal, nt_inld_pad=T)
nn.AvgPl2d(knl_iz, tid=Nn, padding=0, il_md=Fal, nt_inld_pad=T)
nn.AvgPl3d(knl_iz, tid=Nn, padding=0, il_md=Fal, nt_inld_pad=T)
nn.FatinalMaxPl2d(knl_iz, tpt_iz=Nn, tpt_ati=Nn, tn_indi=Fal, _andm_ampl=Nn)
nn.LPPl2d(nm_typ, knl_iz, tid=Nn, il_md=Fal)
nn.AdaptivMaxPl1d(tpt_iz, tn_indi=Fal)
nn.AdaptivMaxPl2d(tpt_iz, tn_indi=Fal)
nn.AdaptivMaxPl3d(tpt_iz, tn_indi=Fal)
nn.AdaptivAvgPl1d(tpt_iz)
nn.AdaptivAvgPl2d(tpt_iz)
nn.AdaptivAvgPl3d(tpt_iz)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Dropout层
nn.Dropout(p=0.5, inplace=False)
nn.Dropout2d(p=0.5, inplace=False)
nn.Dropout3d(p=0.5, inplace=False)
nn.AlphaDropout(p=0.5)
1
2
3
4
常用激活函数
nn.ReLU(inplace=False)
nn.ReLU6(inplace=False)
nn.ELU(alpha=1.0, inplace=False)
nn.SELU(inplace=False)
nn.PReLU(num_parameters=1, init=0.25)
nn.LeakyReLU(negative_slope=0.01, inplace=False)
nn.Threshold(threshold, value, inplace=False)
nn.Hardtanh(min_val=-1, max_val=1, inplace=False, min_value=None, max_value=None)
nn.Sigmoid
nn.LogSigmoid
nn.Tanh
nn.Tanhshrink
nn.Softplus(beta=1, threshold=20)
nn.Softmax(dim=None)
nn.LogSoftmax(dim=None)
nn.Softmax2d
nn.Softmin(dim=None)
nn.Softshrink(lambd=0.5)
nn.Softsign
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
常用损失函数
nn.L1Loss(size_average=True, reduce=True)
nn.MSELoss(size_average=True, reduce=True)
nn.CrossEntropyLoss(weight=None, size_average=True, ignore_index=-100, reduce=True)
nn.NLLLoss(weight=None, size_average=True, ignore_index=-100, reduce=True)
nn.PoissonNLLLoss(log_input=True, full=False, size_average=True, eps=1e-08)
nn.NLLLoss2d(weight=None, size_average=True, ignore_index=-100, reduce=True)
nn.KLDivLoss(size_average=True, reduce=True)
nn.BCELoss(weight=None, size_average=True)
nn.BCEWithLogitsLoss(weight=None, size_average=True)
nn.MarginRankingLoss(margin=0, size_average=True)
nn.HingeEmbeddingLoss(margin=1.0, size_average=True)
nn.MultiLabelMarginLoss(size_average=True)
nn.SmoothL1Loss(size_average=True, reduce=True)
nn.SoftMarginLoss(size_average=True)
nn.CosineEmbeddingLoss(margin=0, size_average=True)
————————————————
版权声明:本文为CSDN博主「sherpahu」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sherpahu/article/details/95935845

pytorch常用函数API简析与汇总——以备查询相关推荐

  1. 全新开源,《Pytorch常用函数函数手册》开放下载!内含200余个函数!

    近期有很多小伙伴在后台咨询有没有关于Pytorch函数使用的学习资料.Pytorch是目前常用的深度学习框架之一,深受学生党的喜爱,小白本人也是使用的Pytorch框架.为了帮助更多小伙伴,小白学视觉 ...

  2. 哈工大博士历时半年整理的《Pytorch常用函数函数手册》开放下载!内含200余个函数!...

    近期有很多小伙伴在公众号后台咨询有没有关于Pytorch函数使用的学习资料.Pytorch是目前常用的深度学习框架之一,深受学生党的喜爱,小白本人也是使用的Pytorch框架.为了帮助更多小伙伴,小白 ...

  3. (Excel)常用函数公式及操作技巧之九:查询和查找引用

    (Excel)常用函数公式及操作技巧之九: 查询和查找引用 --通过知识共享树立个人品牌. 查找顺序公式 =LOOKUP(2,1/(A1:A20<>0),A1:A20) =MATCH(7, ...

  4. oracle常用函数api,Oracle-API OracleAPI、oracle10G函数大全(常用函数)、 联合开发网 - pudn.com...

    Oracle-API 所属分类:Oracle数据库 开发工具:SQL 文件大小:13650KB 下载次数:20 上传日期:2013-09-03 13:09:39 上 传 者:蓝 说明:  Oracle ...

  5. SQL数据分析:sqlzoo官网学习select,where,order by,limit,聚合函数,having,常用函数,窗口函数,表链接,子查询

    SQL数据分析: 2022找工作是学历.能力和运气的超强结合体,遇到寒冬,大厂不招人,可能很多算法学生都得去找开发,测开 测开的话,你就得学数据库,sql,oracle,尤其sql要学,当然,像很多金 ...

  6. OpenCV常用函数极简简介

    1.cvLoadImage:将图像文件加载至内存: 2.cvNamedWindow:在屏幕上创建一个窗口: 3.cvShowImage:在一个已创建好的窗口中显示图像: 4.cvWaitKey:使程序 ...

  7. TensorFlow 学习(七) — 常用函数 api、tf.nn、tf.keras

    0. 四则运算 平方:tf.square(),开方:tf.sqrt() tf.add().tf.sub().tf.mul().tf.div().tf.mod().tf.abs().tf.neg() 1 ...

  8. [Pytorch 常用函数] 激活函数Relu, Leaky Relu

    修正线性单元(Rectified linear unit,ReLU)是神经网络中最常用的激活函数.它保留了 step 函数的生物学启发(只有输入超出阈值时神经元才激活),不过当输入为正的时候,导数不为 ...

  9. pytorch常用函数总结(更新中)

    目录 一. 初始化张量 1. torch.arange()和range() 2. torch.rand().torch.randn().torch.randint().torch.randperm() ...

最新文章

  1. 《PHP和MySQL Web开发从新手到高手(第5版)》一1.7 万事俱备,摩拳擦掌
  2. 百万级并发 Node.js也能行
  3. c++ STL 全排列
  4. 嵌入式软件开发工程师谈软件架构的设计
  5. Win-MASM64汇编语言-CMP/CMPSB/CMPSW/CMPSD/JNE/JCXZ
  6. Java全能手册火了!Redis/Nginx/Dubbo/Spring全家桶/高并发
  7. UVA10625 GNU = GNU'sNotUnix【字符统计】
  8. 《实变函数简明教程》,P63,可测集上的连续函数一定可测
  9. Low-Resource Knowledge-Grounded Dialogue Generation_biji
  10. 编解码学习笔记(九):QuickTime系列
  11. 赤子城科技三年两变:音视频社交成主力军,营收结构稳定性存疑
  12. 香港服务器要个人信息么,香港个人信息应当遵循服务器23.225合法
  13. 乘风破浪的 AI 姐姐,成团首秀献唱 WAIC
  14. 专家齐议尘肺病农民救助难点
  15. 每日一题 LeetCode909. 蛇梯棋 java题解
  16. 内网渗透(十一)之内网信息收集-内网IP扫描和发现
  17. arduino uno + nokia 5110
  18. 科技风PPT汇报模板
  19. Android Studio编译JNI时指定CPU种类
  20. python 支付宝接口_python调用支付宝支付接口流程

热门文章

  1. Boost.Signals 的文档/查看示例
  2. boost::locale::utf8_codecvt用法的测试程序
  3. boost::geometry::centroid用法的测试程序
  4. boost::detail::lowest_bit的测试程序
  5. DCMTK:OFOptional的单元测试
  6. VTK:可视化之SideBySideViewports
  7. VTK:图片之DotProduct
  8. OpenGL渲染水water
  9. C++cycle sort循环排序的实现算法(附完整源码)
  10. C++vigenere cipher维吉尼亚密码算法(附完整源码)