一維张量與二維张量

AI · 9 天前 · 12 人浏览

在這裏先創建一個4*4二維张量,想象下一個正方形由很多個小方塊組成。在這裏 dim 的值為0時,合并的是行,為1時合并的是列。

tensor = torch.ones(4, 4)
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

輸出

tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

那麽到了一維,這裏是 0 ,結果并不是[1,2],[3,4]

a = torch.tensor([1, 2])
b = torch.tensor([3, 4])
torch.cat([a, b], dim=0)  # 结果是 tensor([1, 2, 3, 4]),沿着第 0 维(行)连接

关于 dim=1 代表从列添加的理解是正确的,但这通常是在我们处理二维或更高维度的张量时。

关键的区别在于张量的维度:

  • 一维张量: 只有一个维度,通常我们称之为第 0 维。torch.cat 沿着这个维度连接,相当于将多个向量首尾相连。
  • 二维张量: 有两个维度,第 0 维代表行,第 1 维代表列。torch.catdim=0 时按行连接(上下拼接),在 dim=1 时按列连接(左右拼接)。

** 在一维张量的情况下,dim=1 是不存在的(因为只有一个维度 0)。

本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao