簡體   English   中英

將張量列表轉換為張量的張量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM