【问题标题】:Convert tensor list to tensor of tensors将张量列表转换为张量的张量
【发布时间】:2020-04-16 17:56:29
【问题描述】:

我有一个变量a,它是一堆这样的张量:

[tensor([0.0014, 0.0021, 0.0015, 0.0007, 0.0012, 0.0024, 0.0021, 0.0019, 0.0010,
        0.0010])]
[tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])]

....

当我想在我的代码中执行此操作时:

x = torch.tensor(a, dtype=torch.float)

我收到了这个错误:

ValueError: only one element tensors can be converted to Python scalars

我假设我可能需要像这样转换a 中的每个张量:

[tensor([[0.0014], [0.0021], [0.0015], [0.0007], [0.0012], [0.0024], [0.0021], [0.0019], [0.0010],
        [0.0010]])]
[tensor([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]])]

我的想法对吗?或者我需要什么来避免上述错误?

有什么帮助吗?

【问题讨论】:

    标签: python list pytorch


    【解决方案1】:

    在 pytorch 中,您可以使用 view() 方法来重塑张量。 准确地说,使用此代码:

    t2 = t1.view(t1.shape[0],-1) 其中 t1 是要重塑的张量。

    工作代码:

    t1 = torch.Tensor([1.6455e-04, 1.2067e-04, 4.3461e-04, 2.0265e-04, 1.4014e-04, 2.0691e-04,
            1.2612e-04, 9.2561e-05, 9.4662e-05, 7.3938e-05])
    
    tensor_lst = []
    tensor_lst.append(t1)
    
    res_t = [] #reshaped tensor
    for i in range(len(lst)):
        res_t.append(lst[i].view(lst[i].shape[0],-1))
    
    print(res_t)
    
    

    【讨论】:

    • 我收到了这个错误:AttributeError: 'list' object has no attribute 'view' @Ashish Johnson
    • 这是因为你在列表中使用view方法,你必须访问列表中的张量然后使用.view()方法。如果你能分享代码,我会更正。
    • 我从一开始就使用导致此错误的代码编辑/更新问题,提前感谢@Ashish Johnson
    • @LamaMo 进行更改后,您似乎有一个 2D 张量列表,当您已经在 'a' 中有一个浮动张量列表时,为什么要执行此操作x = torch.tensor(a, dtype=torch.float)?请重新表述问题。还告诉我变量'a'的初始化
    【解决方案2】:

    简单,只需重塑它。假设您的张量/张量存储在一个名为 tlist 的列表中:

    tlist = [t.reshape(-1,1) for t in tlist]
    

    【讨论】:

    • 我收到了这个错误:AttributeError: 'list' object has no attribute 'reshape'
    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 2019-07-29
    • 2021-11-10
    • 2021-10-11
    • 1970-01-01
    • 2022-09-29
    • 2021-01-14
    相关资源
    最近更新 更多