torch.unravel_index¶
- torch.unravel_index(indices, shape)[source][source]¶
将扁平索引的张量转换为坐标张量元组,用于索引指定形状的任意张量。
- 参数
indices (Tensor) – 一个整数张量,包含对应于 shape 指定形状的任意张量展平后版本的索引。所有元素必须在范围
[0, prod(shape) - 1]
内。shape (int, int 序列, 或 torch.Size) – 任意张量的形状。所有元素必须非负。
- 返回
输出中的第
i
个张量对应于shape
的第i
个维度。每个张量的形状与indices
相同,并包含indices
给定的每个扁平索引在第i
个维度上的索引。- 返回类型
示例
>>> import torch >>> torch.unravel_index(torch.tensor(4), (3, 2)) (tensor(2), tensor(0)) >>> torch.unravel_index(torch.tensor([4, 1]), (3, 2)) (tensor([2, 0]), tensor([0, 1])) >>> torch.unravel_index(torch.tensor([0, 1, 2, 3, 4, 5]), (3, 2)) (tensor([0, 0, 1, 1, 2, 2]), tensor([0, 1, 0, 1, 0, 1])) >>> torch.unravel_index(torch.tensor([1234, 5678]), (10, 10, 10, 10)) (tensor([1, 5]), tensor([2, 6]), tensor([3, 7]), tensor([4, 8])) >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (10, 10, 10, 10)) (tensor([[1], [5]]), tensor([[2], [6]]), tensor([[3], [7]]), tensor([[4], [8]])) >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (100, 100)) (tensor([[12], [56]]), tensor([[34], [78]]))