PyTorch torch.searchsorted function
PyTorch torch reference manual
torch.searchsorted is a function in PyTorch used to search a sorted tensor for the position where an element should be inserted. The returned value is the index position where the element should be inserted.
Function definition
torch.searchsorted(sorted_sequence, values, side='left', out_int32=False, right=False)
Parameter Description:
sorted_sequence: a sorted one-dimensional or multi-dimensional tensorvalues: the value to search forside: 'left' or 'right', determining whether to return the left or right insertion positionout_int32: whether to return the int32 typeright: deprecated, use side instead
Usage examples
Example
import
torch
Create a sorted sequence
sorted_seq
=
torch.
tensor
(
[
1
,
3
,
5
,
7
,
9
]
)
Search for the position of a value
values
=
torch.
tensor
(
[
3
,
6
,
8
]
)
y
=
torch.
searchsorted
(
sorted_seq
,
values
)
(
y
)
The output is:
tensor([1, 3, 3])
实例
import torch
# 创建已排序的序列
sorted_seq = torch.tensor([1, 3, 5, 7, 9])
# 使用 side='right' 搜索
values = torch.tensor([3, 6, 8])
y = torch.searchsorted(sorted_seq, values, side='right')
print(y)
输出结果为:
tensor([2, 3, 4])
Example
import
torch
For multidimensional arrays
sorted_seq
=
torch.
tensor
(
[
[
1
,
3
,
5
]
,
[
2
,
4
,
6
]
]
)
values
=
torch.
tensor
(
[
[
1.5
]
,
[
3.5
]
]
)
y
=
torch.
searchsorted
(
sorted_seq
,
values
)
(
y
)
The output is:
tensor([[1],
[1]])