作者:煉己者
本博客所有內(nèi)容以學(xué)習(xí)载庭、研究和分享為主看彼,如需轉(zhuǎn)載,請聯(lián)系本人昧捷,標(biāo)明作者和出處闲昭,并且是非商業(yè)用途,謝謝靡挥!
最近在看swin transformer的代碼序矩,在這里記錄一下遇到的torch.roll的用法。
# swin transformer中移位的操作
class CyclicShift(nn.Module):
def __init__(self, displacement):
super().__init__()
self.displacement = displacement
def forward(self, x):
return torch.roll(x, shifts=(self.displacement, self.displacement), dims=(1, 2))
torch.roll(input, shifts, dims=None) 這個函數(shù)到底是干啥的跋破,咋用的呢簸淀?
簡單說,它就是用來移位的毒返,是順移租幕。input是咱們要移動的tensor向量,shifts是要移動到的位置拧簸,要移動去哪兒劲绪,dims是值在什么方向上(維度)去移動。比如2維的數(shù)據(jù)盆赤,那就兩個方向贾富,橫著或者豎著。對了牺六,關(guān)鍵的一句話颤枪,所有操作針對第一行或者第一列,主要是這個"第一"淑际,下面舉例子給大家做解釋畏纲,自己慢慢體會
>>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(3, 3)
>>> x
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> torch.roll(x, 1, 0)
tensor([[7, 8, 9],
[1, 2, 3],
[4, 5, 6]])
torch.roll(x, 1, 0) 這行代碼的意思就是把x的第一行(0維度)移到1這個位置上,其他位置的數(shù)據(jù)順移春缕。
x——咱們要移動的向量
1——第一行向量要移動到的最終位置
0——從行的角度去移動
再來一個列的例子
>>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(3, 3)
>>> x
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> torch.roll(x, -1, 1)
>>> x
tensor([[2, 3, 1],
[5, 6, 4],
[8, 9, 7]])
torch.roll(x, -1, 1) 這行代碼的意思就是把x的第一列(1維度)移到-1這個位置(最后一個位置)上盗胀,其他位置的數(shù)據(jù)順移。
shifts和dims可以是元組淡溯,其實(shí)就是分步驟去移動读整,再舉個例子
>>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(3, 3)
>>> x
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> torch.roll(x, (0,1), (1,1))
tensor([[3, 1, 2],
[6, 4, 5],
[9, 7, 8]])
torch.roll(x, (0,1), (1,1)) 這行代碼的意思:
第一步,把x的第一列(1維度)移到0這個位置(原地不動)上咱娶,其他位置的數(shù)據(jù)順移米间。(所有數(shù)據(jù)原地不動)
>>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9]).view(3, 3)
>>> x
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> a = torch.roll(x, 0, 1)
>>> a
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
第二步,把a(bǔ)的第一列(1維度)移到1這個位置上膘侮,其他位置的數(shù)據(jù)順移屈糊。
>>> a = torch.roll(x, 0, 1)
>>> a
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> b = torch.roll(a, 1, 1)
>>> b
tensor([[3, 1, 2],
[6, 4, 5],
[9, 7, 8]])
以上便是torch.roll()函數(shù)的用法,大家有疑問可以在底下評論交流琼了,跑跑代碼逻锐,便可迎刃而解
以下是我所有文章的目錄,大家如果感興趣雕薪,也可以前往查看
??戳右邊:打開它昧诱,也許會看到很多對你有幫助的文章