list里面装tensor(pytorch的)如何合并起来

问题简述:

 使用pytorch中tensor时,有时需要将多个tensor合并成一个高维tensor

或者是list中装着多个同纬度的tensor,想让这个list转为tensor

核心方法:

torch.stack()

def stack(tensors: Union[Tuple[Tensor, ...], List[Tensor]], dim: _int=0, *, out: Optional[Tensor]=None) -> Tensor:

代码示范

def listToTensor():
    tensor1=tensor([1,2,3])
    tensor2=tensor([4,5,6])
    tensor_list=list()
    tensor_list.append(tensor1)
    tensor_list.append(tensor2)
    final_tensor=torch.stack(tensor_list)  ###
    print('tensor_list:',tensor_list, '  type:',type(tensor_list))
    print('final_tensor:',final_tensor, '  type',type(final_tensor))
    pass
if __name__=='__main__':
    listToTensor()

 

你可能感兴趣的:(pytorch,python,pytorch)