Shortcuts

torch.combinations

torch.combinations(input, r=2, with_replacement=False) seq

计算给定张量的长度为 rr 的组合。当 with_replacement 设置为 False 时,行为类似于 python 的 itertools.combinations,当 with_replacement 设置为 True 时,行为类似于 itertools.combinations_with_replacement

Parameters
  • 输入 (张量) – 1D 向量。

  • r (int, 可选) – 要组合的元素数量

  • with_replacement (布尔值, 可选) – 是否允许在组合中出现重复

Returns

一个张量等价于将所有输入张量转换为列表,对这些列表执行itertools.combinationsitertools.combinations_with_replacement,最后将结果列表转换为张量。

Return type

张量

示例:

>>> a = [1, 2, 3]
>>> list(itertools.combinations(a, r=2))
[(1, 2), (1, 3), (2, 3)]
>>> list(itertools.combinations(a, r=3))
[(1, 2, 3)]
>>> list(itertools.combinations_with_replacement(a, r=2))
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
>>> tensor_a = torch.tensor(a)
>>> torch.combinations(tensor_a)
tensor([[1, 2],
        [1, 3],
        [2, 3]])
>>> torch.combinations(tensor_a, r=3)
tensor([[1, 2, 3]])
>>> torch.combinations(tensor_a, with_replacement=True)
tensor([[1, 1],
        [1, 2],
        [1, 3],
        [2, 2],
        [2, 3],
        [3, 3]])
优云智算