目的:通过for循环得到的多个tensor,最终拼接起来。
>>> import pytorch
>>> input = torch.randn(2,5)
>>> input.unsqueeze_(1)
tensor([[[-0.1127, 0.1031, -1.7152, -0.1951, 0.8266]],
[[ 0.2320, -0.2719, 1.6631, -1.3010, -0.1101]]])
>>> lt=[]
>>> for t in input:
lt.append(t)
>>> lt
[tensor([[-0.1127, 0.1031, -1.7152, -0.1951, 0.8266]]),
tensor([[ 0.2320, -0.2719, 1.6631, -1.3010, -0.1101]])]
>>> torch.cat(lt,dim=0)
tensor([[-0.1127, 0.1031, -1.7152, -0.1951, 0.8266],
[ 0.2320, -0.2719, 1.6631, -1.3010, -0.1101]])
注意:
假设input
的shape
是(2, 5)
,input
中的每个元素要先增加一维,再放入list
。
>>> input.unsqueeze_(1)
如果没有这一步的话,就无法得到想要的结果,还可能会报错。
>>> input = torch.randn(2,5)
>>> lt = []
>>> for t in input:
lt.append(t)
>>> lt
[tensor([ 1.3861, -0.3191, 1.2268, -0.2041, -1.6669]),
tensor([-0.0951, 1.1444, 0.7381, 0.4155, -0.1998])]
>>> torch.cat(lt, dim=0)
tensor([ 1.3861, -0.3191, 1.2268, -0.2041, -1.6669, -0.0951, 1.1444, 0.7381, 0.4155, -0.1998])
>>> torch.cat(lt, dim=1)
Traceback (most recent call last):
File "/IPython/core/interactiveshell.py", line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "" , line 4, in <module>
torch.cat(lt, dim=1)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
在torch.cat(lt,dim=0)
之前,不必将lt
转为tensor
,否则会报错。
ValueError: only one element tensors can be converted to Python scalars