其將單個維度擴大成更大維度,返回乙個新的tensor,具體看下例:
import torch
a = torch.tensor([[
1],[
2],[
3],[
4]])
# 未使用expand()函式前的a
print
('a.size: '
, a.size())
print
('a: '
, a)
b = a.expand(4,
2)# 使用expand()函式後的輸出
print
('a.size: '
, a.size())
print
('a: '
, a)
print
('b.size: '
, b.size())
print
('b: '
, b)
expand()函式使用前後a沒有發生變化,輸出都是:
a.size:torch.size([4, 1])b 的輸出為:a:12
34[torch.floattensor of size 4x1]
b.size:torch.size([4, 2])b:
1 12 2
3 34 4
[torch.floattensor of size 4x2]
由此得出結論,a通過expand()函式擴充套件某一維度後自身不會發生變化
a = torch.tensor([[
[[1,
2],[
2,3]
,[3,
4],[
4,5]
]]])
b = a.expand(2,
1,4,
2)c = a.expand(1,
2,4,
2)# 使用expand()函式後的輸出
print
('a.size: '
, a.size())
print
('b.size: '
, b.size())
print
('b: '
, b)
print
('c.size: '
, c.size())
print
('c: '
, c)
b2 = b.expand(3,
1,4,
2)# b: torch.size([2, 1, 4, 2])
print
('b2.size: '
, b2.size(
))
輸出:
a.size:torch.size([1, 1, 4, 2])
b.size:torch.size([2, 1, 4, 2])b:
(0 ,0 ,.,.) =
1 22 3
3 44 5
(1 ,0 ,.,.) =
1 22 3
3 44 5
[torch.floattensor of size 2x1x4x2]
c.size:torch.size([1, 2, 4, 2])b2輸出:c:
(0 ,0 ,.,.) =
1 22 3
3 44 5
(0 ,1 ,.,.) =
1 22 3
3 44 5
[torch.floattensor of size 1x2x4x2]
traceback (most recent call last):由此可見,只要是單維度均可進行擴充套件,但是若非單維度會報錯file 「」, line 1, in
runtimeerror: the expanded size of the tensor (3) must match the existing size (2) at non-singleton dimension 0. at /opt/conda/conda-bld/pytorch_1525796793591/work/torch/lib/th/generic/thtensor.c:309
pytorch中的expand方法
1.返回tensor的乙個新檢視,單個維度擴大為更大的尺寸。tensor也可以擴大為更高維,新增加的維度將附在前面。擴大tensor不需要分配新記憶體,只是僅僅新建乙個tensor的檢視,其中通過將stride設為0,一維將會擴充套件位更高維。任何乙個一維的在不分配新記憶體情況下可擴充套件為任意的數...
pytorch常用函式
torch.cat torch.squeeze torch.unsqueeze torch.stack torch.sum torch.sum input dim,out none tensor input tensor 輸入張量 dim int 縮減的維度 out tensor,optional ...
pytorch基礎函式
返回乙個張量,從標準正態分佈 均值為0,方差為1 中抽取的一組隨機數。張量的形狀由引數sizes定義。import torch import torch.nn.functional as f x1 torch.tensor 1,2,3,4 1,3,4,5 3,4,5,6 y11 f.softmax ...