PyTorch torch.argwhere function
PyTorch torch reference manual
torch.argwhere is a function in PyTorch used to return the indices of elements that satisfy a condition. It returns the indices of elements in the input tensor whose value is True (nonzero).
Function definition
torch.argwhere(input)
Parameters:
input(Tensor): the input tensor.
Return Value:
torch.Tensor: Returns a two-dimensional tensor in which each row is the index of an element that satisfies the condition.
Usage examples
Example
import
torch
Create a tensor
x
=
torch.
tensor
(
[
[
1
,
0
,
2
]
,
[
0
,
3
,
0
]
,
[
4
,
5
,
0
]
]
)
(
"Original tensor:"
)
(
x
)
Return the indices of the nonzero elements
indices
=
torch.
argwhere
(
x
)
(
"nIndices of nonzero elements:"
)
(
indices
)
The output is:
原始张量:
tensor([[1, 0, 2],
[0, 3, 0],
[4, 5, 0]])
Index of non-zero elements:
tensor([[0, 0],
[0, 2],
[1, 1],
[2, 0],
[2, 1]])
Example
import
torch
Boolean condition
x
=
torch.
tensor
(
[
[
True
,
False
,
True
]
,
[
False
,
True
,
False
]
,
[
True
,
True
,
False
]
]
)
(
"Boolean tensor:"
)
(
x
)
indices
=
torch.
argwhere
(
x
)
(
"nIndices of True values:"
)
(
indices
)
The output is:
布尔张量:
tensor([[True, False, True],
[False, True, False],
[True, True, False]])
Index of True values:
tensor([[0, 0],
[0, 2],
[1, 1],
[2, 0],
[2, 1]])
Example
import
torch
Find elements greater than a certain value
x
=
torch.
randn
(
3
,
4
)
threshold
=
0
(
"Original tensor:"
)
(
x
)
Find indices of elements greater than threshold
indices
=
torch.
argwhere
(
x >
;
threshold
)
(
f
"nIndices of elements greater than {threshold}:"
)
(
indices
)
You can also use the nonzero function, with the same effect
indices2
=
torch.
nonzero
(
x >
;
threshold
)
(
"nResult of using nonzero:"
)
(
indices2
)
The output is:
原始张量:
tensor([[-1.2345, 0.5678, -0.8901, 1.2345],
[ 0.3456, -0.6789, 0.9012, -0.1234],
[-0.5678, 1.2345, -0.3456, 0.7890]])
Indices of elements greater than 0:
tensor([[0, 1],
[0, 3],
[1, 0],
[1, 2],
[2, 1],
[2, 3]])
Result using nonzero:
tensor([[0, 1],
[0, 3],
[1, 0],
[1, 2],
[2, 1],
[2, 3]])
Example
import
torch
1D tensor
x
=
torch.
tensor
(
[
1
,
0
,
0
,
4
,
0
,
5
,
0
]
)
indices
=
torch.
argwhere
(
x
)
(
"Indices of the 1D tensor:"
)
(
indices.
squeeze
(
)
)
Remove the extra dimension
The output is:
1D张量的索引:
tensor([0, 3, 5])
Example
import
torch
Application: Find elements that satisfy a condition and modify them
x
=
torch.
randn
(
5
,
5
)
Find the indices of all elements greater than 0
pos_indices
=
torch.
argwhere
(
x >
;
0
)
(
"Positions greater than 0 in the original tensor:"
)
(
pos_indices
)
Use these indices to modify values
for
idx
in
pos_indices:
x
[
idx
[
0
]
,
idx
[
1
]
]
=
100
(
"nModified tensor:"
)
(
x
)
Note:torch.argwhere Is torch.nonzero is an alias of it, and the two are functionally identical. It returns element indices, with each row corresponding to the position of an element satisfying the condition in the original tensor.