[英]Convert tensor list to tensor of tensors
我有一个变量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]])]
我的想法对吗? 或者我需要什么来避免上述错误?
请问有什么帮助吗?
在 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)
很简单,重塑它。 假设您的张量/张量存储在一个名为tlist
的列表中:
tlist = [t.reshape(-1,1) for t in tlist]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.