PyTorch torch.combinations function
PyTorch torch reference manual
torch.combinations is a function in PyTorch used to compute all r-combinations of the elements of an input tensor. It returns all possible combinations of length r from the input tensor.
Function definition
torch.combinations(input, r=2, with_replacement=False)
Usage examples
Example
import
torch
Compute all 2-element combinations
x
=
torch.
tensor
(
[
1
,
2
,
3
,
4
]
)
result
=
torch.
combinations
(
x
,
r
=
2
)
(
"Input:"
,
x
)
(
"2-element combinations:"
)
(
result
)
tensor([[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4]])
3-element combinations
result3
=
torch.
combinations
(
x
,
r
=
3
)
(
"3-element combinations:"
)
(
result3
)
Combinations with replacement (with_replacement=True)
result_with_replacement
=
torch.
combinations
(
x
,
r
=
2
,
with_replacement
=
True
)
(
"2-element combinations with replacement:"
)
(
result_with_replacement
)