PyTorch torch.bucketize Function
Pytorch torch Reference Manual
torch.bucketizeIt is a PyTorch function used for bucketized indexing. It maps input values to corresponding bucket indices, performing a binary search based on a boundary array. It is often used to discretize continuous values or for binning operations.
Function Definition
torch.bucketize(input, boundaries, right=False, out_int32=False, **kwargs)
Usage Example
Example
import torch
# Basic usage: bucketized indexing
boundaries = torch.tensor([0, 1, 2, 3, 4])
values = torch.tensor([0.5, 1.5, 2.5, 3.5, 0.2, 2.0])
result = torch.bucketize(values, boundaries)
print("Boundaries:", boundaries)
print("Values:", values)
print("Bucket indices:", result)
# Output: tensor([1, 2, 3, 4, 0, 2])
# right=True means the boundaries are right-closed intervals
result_right = torch.bucketize(values, boundaries, right=True)
print("right=True bucket indices:", result_right)
# Output: tensor([0, 1, 2, 3, 0, 1])
# Multi-dimensional input
values = torch.tensor([[0.5, 1.5], [2.5, 3.5]])
result = torch.bucketize(values, boundaries)
print("Multi-dimensional input result:", result)
# Basic usage: bucketized indexing
boundaries = torch.tensor([0, 1, 2, 3, 4])
values = torch.tensor([0.5, 1.5, 2.5, 3.5, 0.2, 2.0])
result = torch.bucketize(values, boundaries)
print("Boundaries:", boundaries)
print("Values:", values)
print("Bucket indices:", result)
# Output: tensor([1, 2, 3, 4, 0, 2])
# right=True means the boundaries are right-closed intervals
result_right = torch.bucketize(values, boundaries, right=True)
print("right=True bucket indices:", result_right)
# Output: tensor([0, 1, 2, 3, 0, 1])
# Multi-dimensional input
values = torch.tensor([[0.5, 1.5], [2.5, 3.5]])
result = torch.bucketize(values, boundaries)
print("Multi-dimensional input result:", result)
Other Extensions