pytorch常用函数API简析与汇总——以备查询
版權(quán)聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接和本聲明。
本文鏈接: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層
常用激活函數(shù)
常用損失函數(shù)
Tensor
運算
操作?? ?功能
torch.abs?? ?絕對值
torch.add?? ?
torch.clamp?? ?裁剪
torch.div?? ?
torch.mul?? ?逐元素求積
torch.pow?? ?
torch.mm?? ?矩陣乘法
torch.mv?? ?矩陣向量乘法
變換
torch.Tensor.transpose()&torch.Tensor.permute()
transpose一次只能操作矩陣的兩個維度,只接收兩個維度的參數(shù)。
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是對數(shù)據(jù)沿著某一個維度對seq中的Tensor進行拼接,操作之后總維數(shù)不變,只在統(tǒng)一維度進行拼接。
torch.cat(seq, dim=0, out=None) → Tensor
參數(shù):
seq (sequence of Tensors) - Python序列或相同類型的張量序列
dim (int, optional) - 沿著此維度連接張量
out (Tensor, optional) - 輸出參數(shù)
除了在拼接的維度外,其余維度必須相等才能拼接。
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是在增加新的維度后進行“堆疊”,而不是直接拼接。會增加維度。
在對數(shù)據(jù)進行加載組合為一個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)壓縮,去掉元素數(shù)為1的dim_n的維度。
torch.squeeze(input, dim=None, out=None) → Tensor
參數(shù):
input (Tensor) – 輸入張量
dim (int, optional) – 如果給定,則只會在給定維度壓縮
out (Tensor, optional) – 輸出張量
unsqueeze(dim_n)增加dim_n維度,元素數(shù)目為1,與squeeze相反。
a=torch.rand(2,1,4)#torch.Size([2,1,4])
b=a.squeeze()#torch.Size([2,4]),去掉了元素個數(shù)為1的第二個維度
c=a.squeeze(1)#torch.Size([2,4]),同上
d=a.squeeze(2)#torch.Size([2,1,4]),第三個維度的元素個數(shù)不為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
擴大張量,并且將張量復(fù)制使之變?yōu)閷?yīng)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)
擴大張量,并且將張量變?yōu)閷?yīng)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的內(nèi)存是整塊的。有些tensor并不是占用一整塊內(nèi)存,而是由不同的數(shù)據(jù)塊組成,而tensor的view()操作依賴于內(nèi)存是整塊的,這時只需要執(zhí)行contiguous()這個函數(shù),把tensor變成在內(nèi)存中連續(xù)分布的形式。判斷是否contiguous用torch.Tensor.is_contiguous()函數(shù)
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
因此,在調(diào)用view之前最好先contiguous一下,x.contiguous().view() 。
torch.Tensor.view(*args)->Tensor
參數(shù):
args (torch.Size or int…) - 理想的指定尺寸
返回具有相同數(shù)據(jù),但是形狀與args所述相同的新的Tensor
a=torch.rand(4,4)#torch.Size([4,4])
b=x.view(16)#torch.Size([16])
1
2
常用層
nn.Sequential()
參數(shù):若干其他層
torch.nn.Sequential 其實就是 Sequential 容器,該容器將一系列操作按先后順序給包起
來,方便重復(fù)使用。將若干簡單的層組合起來,方便結(jié)構(gòu)顯示與重用。
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()
參數(shù):輸入維度,輸出維度
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要轉(zhuǎn)置
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()
參數(shù):in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True
輸入大小、輸出大小、卷積核個數(shù)groups、卷積核大小kernel_size、滑動步長stride和填充量padding
kernel_size, stride, padding, dilation 不但可以是一個單個的int——表示在高度和寬度使用這個相同的int作為參數(shù)
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
常用激活函數(shù)
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
常用損失函數(shù)
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)
————————————————
版權(quán)聲明:本文為CSDN博主「sherpahu」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/sherpahu/article/details/95935845
總結(jié)
以上是生活随笔為你收集整理的pytorch常用函数API简析与汇总——以备查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch中的pre-train函数
- 下一篇: pytorch载入预训练模型后,训练指定