Pytorch閱讀文檔之torch.cat ,torch.split() and torch.chunk(),torch.stack()函數

Pytorch閱讀文檔之torch.cat (),torch.split() and torch.chunk()函數

torch.cat ()函數

torch.cat(tensors, dim=0, out=None) → Tensor
#在給定維度上連接給定序列張量的序列。
#所有張量必須具有相同的形狀(在連接尺寸中除外)或爲空。
#torch.cat()可以看作是torch.split()和torch.chunk()的逆運算。
#通過示例可以更好地瞭解torch.cat()
#example
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 0)
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 1)
tensor([[ 0.6580, -1.0969, -0.4614,  0.6580, -1.0969, -0.4614,  0.6580,
         -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497, -0.1034, -0.5790,  0.1497, -0.1034,
         -0.5790,  0.1497]])
>>> x = torch.randn(2, 3, 3)
>>> torch.cat((x, x, x), -3).size()
torch.Size([6, 3, 3])
>>> torch.cat((x, x, x), 0).size()
torch.Size([6, 3, 3])
>>> torch.cat((x, x, x), -2).size()
torch.Size([2, 9, 3])
>>> torch.cat((x, x, x), 1).size()
torch.Size([2, 9, 3])

torch.split()函數

torch.split(tensor, split_size_or_sections, dim=0)
#將張量拆分爲多個塊。
#如果split_size_or_sections是整數類型,則張量將被分成相等大小的塊(如果可能)。
#如果沿着給定維度dim的張量大小不能被split_size整除,則最後一個塊會更小。 
#如果split_size_or_sections是一個列表,則張量將根據split_size_or_sections分爲len(split_size_or_sections)個塊,其大小爲dim。
#tensor (Tensor) – tensor to split.
#split_size_or_sections (int) or (list(int)) – 單個塊的大小或每個塊的大小列表
#dim (int) – 分割張量的尺寸

torch.chunk()函數

torch.chunk(input, chunks, dim=0) → List of Tensors
#將張量拆分爲特定數量的塊。 
#如果沿着給定維度dim的張量大小無法被塊整除,則最後一個塊將更小。
#input (Tensor) – the tensor to split
#chunks (int) – 要返回的塊數
#dim (int) – 分割張量的尺寸

torch.stack()函數

#將張量的序列沿新維度連接起來。 所有張量都必須具有相同的大小。
#example
>>> x = torch.randn(2, 3)
>>> torch.stack((x, x, x), 0).size()
torch.Size([3, 2, 3])
>>> torch.stack((x, x, x), 1).size()
torch.Size([2, 3, 3])
>>> torch.stack((x, x, x), 2).size()
torch.Size([2, 3, 3])
>>> torch.stack((x, x, x), 3).size()
IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)
發佈了79 篇原創文章 · 獲贊 26 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章