【问题标题】:An easy way to create a torch tensor from multiple elements of tuple through concatenate通过连接从元组的多个元素创建火炬张量的简单方法
【发布时间】:2021-09-12 14:06:43
【问题描述】:

输入

我有如下列表

r1 = [([[[1, 2, 3], [1, 2, 3]], 
        [[4, 5, 6], [4, 5, 6]]],
       [[[7, 8], [7, 8]], 
        [[9, 10], [9, 10]]]),

      ([[[11, 12, 13], [11, 12, 13]], 
        [[14, 15, 16], [14, 15, 16]]],
       [[[17, 18], [17, 18]], 
        [[19, 20], [19, 20]]])]

我将根据上面的输入制作 2 个火炬张量。

我想要的输出如下

输出

output = 
[tensor([[[ 1,  2,  3],
          [ 1,  2,  3]],
 
         [[ 4,  5,  6],
          [ 4,  5,  6]],
 
         [[11, 12, 13],
          [11, 12, 13]],
 
         [[14, 15, 16],
          [14, 15, 16]]]), 

 tensor([[[ 7,  8],
          [ 7,  8]],
 
         [[ 9, 10],
          [ 9, 10]],
 
         [[17, 18],
          [17, 18]],
 
         [[19, 20],
          [19, 20]]])]

我的代码如下。

output = []
for i in range(len(r1[0])):
    templates = []
    for j in range(len(r1)):
        templates.append(torch.tensor(r1[j][i]))
        template = torch.cat(templates)
    output.append(template)

有没有更简单或更容易的方法来获得我想要的结果?

【问题讨论】:

    标签: python list pytorch tensor


    【解决方案1】:

    这样就可以了:

    output = [torch.Tensor([*a, *b]) for a, b in zip(*r1)]
    

    它先将两个列表的对应项连接起来,然后创建张量

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2022-11-04
      • 2021-08-25
      • 2021-07-08
      • 2021-12-11
      • 2020-04-16
      • 2020-08-27
      • 2017-02-23
      • 2022-07-20
      相关资源
      最近更新 更多