PyTorch函數(shù)torch.cat與torch.stac的區(qū)別小結(jié)
更新時間:2023年09月08日 11:19:57 作者:枯木何日可逢春
Pytorch中常用的兩個拼接函數(shù)torch.cat() 和 torch.stack(),本文主要介紹了這兩個函數(shù)的用法加區(qū)別,具有一定的參考價值,感興趣的可以了解一下
一、torch.cat與torch.stack的區(qū)別
torch.cat
用于在給定的維度上連接多個張量,它將這些張量沿著指定維度堆疊在一起。
torch.stack
用于在新的維度上堆疊多個張量,它會創(chuàng)建一個新的維度,并將這些張量沿著這個新維度堆疊在一起。
二、torch.cat
Example1:
import torch tensor1 = torch.tensor([[1, 2], [3, 4]]) tensor2 = torch.tensor([[5, 6], [7, 8]]) result1 = torch.cat((tensor1, tensor2), dim=0) result2 = torch.cat((tensor1, tensor2), dim=1) print(result1.shape) print(result1) print(result2.shape) print(result2)
torch.Size([4, 2]) tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) torch.Size([2, 4]) tensor([[1, 2, 5, 6], [3, 4, 7, 8]])
三、torch.stack
Example1:
import torch tensor1 = torch.tensor([1, 2, 3]) tensor2 = torch.tensor([4, 5, 6]) result1 = torch.stack((tensor1, tensor2), dim=0) result2 = torch.stack((tensor1, tensor2), dim=1) print(result1.shape) print(result1) print(result2.shape) print(result2)
torch.Size([2, 3]) tensor([[1, 2, 3], [4, 5, 6]]) torch.Size([3, 2]) tensor([[1, 4], [2, 5], [3, 6]])
Example2:
import torch tensor1 = torch.tensor([[1, 2], [3, 4], [5, 6]]) tensor2 = torch.tensor([[7, 8], [9, 10], [11, 12]]) tensor3 = torch.tensor([[13, 14], [15, 16], [17, 18]]) result1 = torch.stack((tensor1, tensor2, tensor3), dim=0) result2 = torch.stack((tensor1, tensor2, tensor3), dim=1) print(result1.shape) print(result1) print(result2.shape) print(result2)
torch.Size([3, 3, 2]) tensor([[[ 1, 2], [ 3, 4], [ 5, 6]], [[ 7, 8], [ 9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]]]) torch.Size([3, 3, 2]) tensor([[[ 1, 2], [ 7, 8], [13, 14]], [[ 3, 4], [ 9, 10], [15, 16]], [[ 5, 6], [11, 12], [17, 18]]])
到此這篇關(guān)于PyTorch函數(shù)torch.cat與torch.stac的區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)PyTorch torch.cat與torch.stac 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中l(wèi)ist列表添加元素的3種方法總結(jié)
這篇文章主要介紹了Python中l(wèi)ist列表添加元素的3種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01