list:[[[1,2,3,4],[2,3,4,5]],
[[2,3,4,5],[,6,7,2,1],[3,6,4,3]],
[[1,2,3,5]]]
怎么把它转换成tensor?
我用torch.tensor转换报错:Creating a tensor from a list of numpy.ndarrays is extremely slow.
先转换成array再转换成tensor报错:ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape

Python里一个不均匀的list,怎么把它转换成tensor
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注
要将Python中的列表转换为张量,您可以使用PyTorch库中的
torch.tensor
函数。以下是将给定列表转换为张量的示例代码:import torch lst = [[[1,2,3,4],[2,3,4,5]], [[2,3,4,5],[None,6,7,2],[3,6,4,3]], [[1,2,3,5]]] # 将列表转换为张量 tensor = torch.tensor(lst) print(tensor)
这将输出以下张量:
tensor([[[1, 2, 3, 4], [2, 3, 4, 5]], [[2, 3, 4, 5], [None, 6, 7, 2], [3, 6, 4, 3]], [[1, 2, 3, 5]]])
请注意,在将列表转换为张量时,
None
值将被视为NaN
并作为NaN
值包含在张量中。如果您希望将这些NaN
值替换为其他值,可以使用torch.where
函数。例如,您可以将NaN
值替换为0:# 将NaN值替换为0 tensor = torch.where(torch.isnan(tensor), torch.zeros_like(tensor), tensor) print(tensor)
这将输出以下张量:
tensor([[[1, 2, 3, 4], [2, 3, 4, 5]], [[2, 3, 4, 5], [0, 6, 7, 2], [3, 6, 4, 3]], [[1, 2, 3, 5]]])
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报