最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch中torch.cat和torch.stack的區(qū)別小結(jié)

 更新時(shí)間:2025年12月12日 10:16:13   作者:coderxiaohan  
本文主要介紹pytorch中的stack和cat的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

torch.cat 和 torch.stack 是 PyTorch 中用于組合張量的兩個(gè)常用函數(shù),它們的核心區(qū)別在于輸入張量的維度和輸出張量的維度變化。以下是詳細(xì)對(duì)比:

1.torch.cat (Concatenate)

作用:沿現(xiàn)有維度拼接多個(gè)張量,不創(chuàng)建新維度

輸入要求:所有張量的形狀必須除拼接維度外完全相同。

語法

torch.cat(tensors, dim=0)  # dim 指定拼接的維度

示例

a = torch.tensor([[1, 2], [3, 4]])  # shape (2, 2)
b = torch.tensor([[5, 6]])           # shape (1, 2)

# 沿 dim=0 拼接(行方向)
c = torch.cat([a, b], dim=0)
print(c)
# tensor([[1, 2],
#         [3, 4],
#         [5, 6]])  # shape (3, 2)

特點(diǎn)

  • 拼接后的張量在指定維度上的大小是輸入張量該維度大小的總和。
  • 其他維度必須完全一致。

2. torch.stack

作用:沿新維度堆疊多個(gè)張量,創(chuàng)建新維度

輸入要求:所有張量的形狀必須完全相同。

語法

torch.stack(tensors, dim=0)  # dim 指定新維度的位置

示例

a = torch.tensor([1, 2])  # shape (2,)
b = torch.tensor([3, 4])  # shape (2,)

# 沿新維度 dim=0 堆疊
c = torch.stack([a, b], dim=0)
print(c)
# tensor([[1, 2],
#         [3, 4]])  # shape (2, 2)

# 沿新維度 dim=1 堆疊
d = torch.stack([a, b], dim=1)
print(d)
# tensor([[1, 3],
#         [2, 4]])  # shape (2, 2)

特點(diǎn)

  • 輸出張量比輸入張量多一個(gè)維度。
  • 適用于將多個(gè)相同形狀的張量合并為批次(如 batch_size 維度)。

3. 關(guān)鍵區(qū)別總結(jié)

4. 直觀對(duì)比示例

假設(shè)有兩個(gè)張量:

x = torch.tensor([1, 2])  # shape (2,)
y = torch.tensor([3, 4])  # shape (2,)

torch.cat 結(jié)果:

torch.cat([x, y], dim=0)  # tensor([1, 2, 3, 4]), shape (4,)

torch.stack 結(jié)果:

torch.stack([x, y], dim=0)  # tensor([[1, 2], [3, 4]]), shape (2, 2)

5. 如何選擇?

  • 用 torch.cat 當(dāng)需要擴(kuò)展現(xiàn)有維度(如拼接多個(gè)特征圖)。
  • 用 torch.stack 當(dāng)需要創(chuàng)建新維度(如構(gòu)建批次數(shù)據(jù)或堆疊不同模型的輸出)

通過理解兩者的維度變化邏輯,可以避免常見的形狀錯(cuò)誤(如 size mismatch)。 

到此這篇關(guān)于pytorch中torch.cat和torch.stack的區(qū)別小結(jié)的文章就介紹到這了,更多相關(guān)pytorch torch.cat和torch.stack內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

大埔县| 阆中市| 慈利县| 武义县| 盈江县| 曲松县| 汕头市| 松滋市| 建阳市| 忻城县| 丰城市| 边坝县| 嫩江县| 轮台县| 黑山县| 永登县| 曲周县| 兖州市| 凤山市| 普兰店市| 西安市| 台湾省| 惠州市| 朔州市| 饶河县| 砀山县| 云阳县| 武冈市| 澄迈县| 涟水县| 达拉特旗| 古交市| 秦安县| 镇远县| 加查县| 长海县| 历史| 阳曲县| 蓬莱市| 嫩江县| 盘锦市|