---
title: Retrieval R-Precision
description: Compute IR R-Precision.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/retrieval/r_precision'
---
# Retrieval R-Precision {#retrieval-r-precision}

## Module Interface {#module-interface}

### `class torchmetrics.retrieval.RetrievalRPrecision(empty_target_action='neg', ignore_index=None, aggregation='mean', **kwargs)` {#torchmetrics.retrieval.RetrievalRPrecision}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.8.2/src/torchmetrics/retrieval/r_precision.py#L28-L137)

Compute [IR R-Precision](https://en.wikipedia.org/wiki/Evaluation_measures_\(information_retrieval\)#R-precision).

Works with binary target data. Accepts float predictions from a model output.

As input to `forward` and `update` the metric accepts the following input:

*   `preds` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")): A float tensor of shape `(N, ...)`
    
*   `target` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")): A long or bool tensor of shape `(N, ...)`
    
*   `indexes` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")): A long tensor of shape `(N, ...)` which indicate to which query a prediction belongs
    

As output to `forward` and `compute` the metric returns the following output:

*   `rp` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")): A single-value tensor with the r-precision of the predictions `preds` w.r.t. the labels `target`.
    

All `indexes`, `preds` and `target` must have the same dimension and will be flatten at the beginning, so that for example, a tensor of shape `(N, M)` is treated as `(N * M, )`. Predictions will be first grouped by `indexes` and then will be computed as the mean of the metric over each query.

Parameters:

*   **empty\_target\_action** ([`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.14)")) –
    
    Specify what to do with queries that do not have at least a positive `target`. Choose from:
    
    *   `'neg'`: those queries count as `0.0` (default)
        
    *   `'pos'`: those queries count as `1.0`
        
    *   `'skip'`: skip those queries; if all queries are skipped, `0.0` is returned
        
    *   `'error'`: raise a `ValueError`
        
    
*   **ignore\_index** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.14)")\[[`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.14)")\]) – Ignore predictions where the target is equal to this number.
    
*   **aggregation** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.14)")\[`'mean'`, `'median'`, `'min'`, `'max'`\], [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.14)")\]) –
    
    Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor and returns a scalar value or one of the following strings:
    
    *   `'mean'`: average value is returned
        
    *   `'median'`: median value is returned
        
    *   `'max'`: max value is returned
        
    *   `'min'`: min value is returned
        
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.14)")) – Additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.8.2/user-guide/overview.md#metric-kwargs) for more info.
    

Raises:

*   [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.14)") – If `empty_target_action` is not one of `error`, `skip`, `neg` or `pos`.
    
*   [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.14)") – If `ignore_index` is not None or an integer.
    

Example

```python
>>> from torch import tensor
>>> from torchmetrics.retrieval import RetrievalRPrecision
>>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
>>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
>>> target = tensor([False, False, True, False, True, False, True])
>>> p2 = RetrievalRPrecision()
>>> p2(preds, target, indexes=indexes)
tensor(0.7500)
```

#### `plot(val=None, ax=None)` {#torchmetrics.retrieval.RetrievalRPrecision.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.8.2/src/torchmetrics/retrieval/r_precision.py#L97-L137)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.14)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")\], [`None`](https://docs.python.org/3/library/constants.html#None "(in Python v3.14)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.14)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.1)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.14)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.1)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.1)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/library/exceptions.html#ModuleNotFoundError "(in Python v3.14)") – If matplotlib is not installed

```python
>>> import torch
>>> from torchmetrics.retrieval import RetrievalRPrecision
>>> # Example plotting a single value
>>> metric = RetrievalRPrecision()
>>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
>>> fig_, ax_ = metric.plot()
```

[![../../\_images/r\_precision-1.png](/docs/torchmetrics/1.8.2/static/_images/r_precision-1.png)](/docs/torchmetrics/1.8.2/static/_images/r_precision-1.png)

```python
>>> import torch
>>> from torchmetrics.retrieval import RetrievalRPrecision
>>> # Example plotting multiple values
>>> metric = RetrievalRPrecision()
>>> values = []
>>> for _ in range(10):
...     values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))))
>>> fig, ax = metric.plot(values)
```

[![../../\_images/r\_precision-2.png](/docs/torchmetrics/1.8.2/static/_images/r_precision-2.png)](/docs/torchmetrics/1.8.2/static/_images/r_precision-2.png)

## Functional Interface {#functional-interface}

### `torchmetrics.functional.retrieval.retrieval_r_precision(preds, target)` {#torchmetrics.functional.retrieval.retrieval_r_precision}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.8.2/src/torchmetrics/functional/retrieval/r_precision.py#L20-L51)

Compute the r-precision metric for information retrieval.

R-Precision is the fraction of relevant documents among all the top `k` retrieved documents where `k` is equal to the total number of relevant documents.

`preds` and `target` should be of the same shape and live on the same device. If no `target` is `True`, `0` is returned. `target` must be either bool or integers and `preds` must be `float`, otherwise an error is raised. If you want to measure Precision@K, `top_k` must be a positive integer.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")) – estimated probabilities of each document to be relevant.
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")) – ground truth about each document being relevant or not.
    

Return type:

[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.13)")

Returns:

A single-value tensor with the r-precision of the predictions `preds` w.r.t. the labels `target`.

Example

```python
>>> preds = tensor([0.2, 0.3, 0.5])
>>> target = tensor([True, False, True])
>>> retrieval_r_precision(preds, target)
tensor(0.5000)
```

---

**Navigation**

- Parent: [Retrieval](/docs/torchmetrics/1.8.2/retrieval.md)
