将张量表转换为张量的张量

2024-10-16 20:51:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量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]])]

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

需要帮忙吗


Tags: to代码only错误torchelementbefloat
2条回答

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

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

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

相关问题 更多 >