当前位置:网站首页>torch. Tensor splicing and list (tensors)

torch. Tensor splicing and list (tensors)

2022-06-25 12:51:00 Yancexi

Construct list(tensors)

Create a list of tensors , as well as 2 The tensor is as follows :

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)

Before stacking stack Function to give a little explanation .Stack operation , First upgrade dimension , Re amplification . Reference resources stack And cat. Stack the tensors , Requiring tensor shape Agreement :

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]]])

however , If you want to use stack Replace the above cat operation , May be an error , because stack requirement Two input shape Exactly the same , and cat Non spliced parts are allowed to be different . except torch.cat outside , You can also use list.append Complete the above operations .

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]])]

be aware ,list.append() Can not only stack the same shape tensors, And can accommodate different shape Of tensor, It's a tensor Containers ! But I have the following problems in the process of using low-level error , Please beware of :

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

    e = a.append(b)
    print(e)  #  Empty !

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 Nothing new will be returned in the process , Only from list_x In order to get .
The end , And the flower .

原网站

版权声明
本文为[Yancexi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251210274513.html