Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.searchsorted function

PyTorch torch.searchsorted function


PyTorch torch reference manual 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:


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

)

print

(

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

)

print

(

y

)

The output is:

tensor([[1],

        [1]])


PyTorch torch reference manual Pytorch torch Reference Manual