如何将字典中所有二维值拼接为PyTorch张量?
将字典中二维数组按行拼接为PyTorch张量的解决方案
可以通过以下简洁步骤实现需求:
- 把字典内的每个二维列表转换为PyTorch张量
- 沿着**列维度(dim=1)**拼接所有张量(所有输入的行数一致,满足拼接前提)
完整代码如下:
import torch D = {'a': [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'b': [[1, 1], [1, 1], [1, 1]], 'c': [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]] } # 转换字典值为张量列表 tensor_list = [torch.tensor(matrix) for matrix in D.values()] # 沿列维度拼接张量 output_tensor = torch.cat(tensor_list, dim=1) print(output_tensor)
运行后会输出预期结果:
tensor([[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2], [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2], [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]])
关键说明
torch.tensor()负责将Python二维列表转换为PyTorch张量,完整保留原二维结构torch.cat()的dim=1参数指定拼接方向为列方向,确保每一行的元素按顺序合并;若误设为dim=0则会按行堆叠,不符合需求
内容的提问来源于stack exchange,提问作者core_not_dumped
相关产品推荐
相关产品推荐

