torch.tensor拼接與list(tensors)


此文轉載自:https://blog.csdn.net/weixin_43543177/article/details/110206274

Construct list(tensors)

創建一個包含張量的列表,以及2個張量如下:

import toroch

a = [torch.tensor([[0.7, 0.3], [0.2, 0.8]]), 
     torch.tensor([[0.5, 0.9], [0.5, 0.5]])]
b = torch.tensor([[0.1, 0.9], [0.3, 0.7]])
c = torch.tensor([[0.1, 0.9, 0.5], [0.3, 0.7, 0.0]])

To stack list(tensors)

堆疊之前對stack函數做一點說明。Stack操作,先升維,再擴增。參考stack與cat。對張量進行堆疊操作,要求張量的shape一致:

stack1 = torch.stack(a)  # default: dim=0, [2, 2, 2]
print(stack1)
stack2 = torch.stack((stack1, b), 0)
print(stack2)

output:

 tensor([[[0.7000, 0.3000],
     [0.2000, 0.8000]],
    [[0.5000, 0.9000],
     [0.5000, 0.5000]]])

RuntimeError: 
stack expects each tensor to be equal size, but got [2, 2, 2] at entry 0 and [2, 2] at entry 1

To concatenate list(tensors)

c = torch.cat([torch.stack(a), b[None]], 0)
# (2, 2, 2), (1, 2, 2) ⇒ (3, 2, 2)
print(c)

Output:

   tensor([
   [[0.7000, 0.3000],
     [0.2000, 0.8000]],

   [[0.5000, 0.9000],
     [0.5000, 0.5000]],

   [[0.1000, 0.9000],
     [0.3000, 0.7000]]])

但是,如果要使用stack替代上述cat操作,則會報錯,因為stack要求兩個輸入的shape完全相同,而cat允許非拼接部分不同。除了torch.cat以外,也可以使用list.append完成以上操作。

a.append(b)
print(a)
a.append(c)
print(a)
[tensor([[0.7000, 0.3000],[0.2000, 0.8000]]),
tensor([[0.5000, 0.9000], [0.5000, 0.5000]]), 
tensor([[0.1000, 0.9000], [0.3000, 0.7000]])]

[tensor([[0.7000, 0.3000], [0.2000, 0.8000]]), 
tensor([[0.5000, 0.9000], [0.5000, 0.5000]]), 
tensor([[0.1000, 0.9000], [0.3000, 0.7000]]), 
tensor([[0.1000, 0.9000, 0.5000],
       [0.3000, 0.7000, 0.0000]])]

注意到,list.append()不僅可以堆疊同形狀的tensors,而且可以容納不同shape的tensor,是一個tensor容器!但是本人在使用過程中出現了以下 low-level 錯誤,請讀者謹防:

    d = []
    d.append(a), d.append(b)
    print(d)

    e = a.append(b)
    print(e)  # 空的!

Output:

[[tensor([[0.7000, 0.3000],
        [0.2000, 0.8000]]), tensor([[0.5000, 0.9000],
        [0.5000, 0.5000]])], tensor([[0.1000, 0.9000],
        [0.3000, 0.7000]])]
None

list_x.append 過程中不會返回新的東西,只能從list_x中獲取。
完結,撒花。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM