Pytorch Torch Round
## PyTorch: torch.round
In PyTorch, `torch.round` is a utility function used to round the elements of a tensor to the nearest integer or to a specified number of decimal places.
This tutorial provides a comprehensive guide to using `torch.round`, including its syntax, parameters, behavior, and practical code examples.
---
## Introduction to torch.round
The `torch.round` function performs element-wise rounding on an input tensor. By default, it rounds values to the nearest integer. If a value is exactly halfway between two integers (e.g., `0.5` or `1.5`), PyTorch uses **round-to-even** (also known as banker's rounding) to resolve ties. This means it rounds to the nearest even integer (e.g., `0.5` rounds to `0.0`, and `1.5` rounds to `2.0`).
Starting from PyTorch 1.11, you can also specify the `decimals` parameter to round to a specific number of decimal places.
---
## Syntax and Parameters
### Syntax
```python
torch.round(input, *, decimals=0, out=None) -> Tensor
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `input` | `Tensor` | The input tensor containing the values to be rounded. |
| `decimals` | `int` (Optional) | The number of decimal places to round to (default is `0`). If `decimals` is negative, it rounds to the left of the decimal point (e.g., tens, hundreds). |
| `out` | `Tensor` (Optional) | The output tensor where the result will be written. |
### Return Value
* Returns a new tensor with the rounded values, having the same shape and data type as the `input`.
---
## Code Examples
### Example 1: Basic Rounding to Nearest Integer
This example demonstrates basic element-wise rounding. Note how PyTorch handles halfway cases (like `0.5` and `1.5`) using the round-to-even rule.
```python
import torch
# Create a tensor with floating-point numbers
x = torch.tensor([0.1, 0.5, 0.9, 1.2, 1.5])
# Round to the nearest integer
result = torch.round(x)
print("Input Tensor: ", x)
print("Rounded Tensor:", result)
```
**Output:**
```text
Input Tensor: tensor([0.1000, 0.5000, 0.9000, 1.2000, 1.5000])
Rounded Tensor: tensor([0., 0., 1., 1., 2.])
```
*Note: `0.5` rounds down to `0.0` (even), while `1.5` rounds up to `2.0` (even).*
---
### Example 2: Rounding to a Specific Number of Decimals
You can use the `decimals` parameter to round to a specific decimal place.
```python
import torch
# Create a tensor with high-precision floats
y = torch.tensor([1.234, 5.678])
# Round to 2 decimal places
result_decimals = torch.round(y, decimals=2)
print("Input Tensor: ", y)
print("Rounded Tensor (2 decimals):", result_decimals)
```
**Output:**
```text
Input Tensor: tensor([1.2340, 5.6780])
Rounded Tensor (2 decimals): tensor([1.2300, 5.6800])
```
---
### Example 3: Rounding to the Left of the Decimal Point
By passing a negative integer to the `decimals` parameter, you can round to the nearest tens, hundreds, etc.
```python
import torch
z = torch.tensor([123.4, 567.8])
# Round to the nearest tens (decimals = -1)
result_tens = torch.round(z, decimals=-1)
print("Input Tensor: ", z)
print("Rounded Tensor (nearest tens):", result_tens)
```
**Output:**
```text
Input Tensor: tensor([123.4000, 567.8000])
Rounded Tensor (nearest tens): tensor([120., 570.])
```
---
### Example 4: In-place Rounding
If you want to modify the tensor in place without allocating new memory, you can use the in-place version of the function: `round_()`.
```python
import torch
data = torch.tensor([1.7, 2.4, 3.5])
# Perform in-place rounding
data.round_()
print("Modified Tensor:", data)
```
**Output:**
```text
Modified Tensor: tensor([2., 2., 4.])
```
---
## Key Considerations
1. **Round-to-Even Rule (Ties to Even):**
When rounding to the nearest integer, values that are exactly halfway between two integers (e.g., `0.5`, `1.5`, `-2.5`) are rounded to the nearest *even* integer. This minimizes cumulative rounding errors in large datasets compared to always rounding up.
2. **Data Types:**
`torch.round` supports floating-point tensor types (e.g., `float32`, `float64`, `float16`). If you pass an integer tensor, the function returns the tensor unchanged.
3. **Performance:**
Like most PyTorch operations, `torch.round` is fully vectorized and runs efficiently on both CPU and GPU (CUDA) devices.
YouTip