> For the complete documentation index, see [llms.txt](https://docs.tensorleap.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/decorators/tensorleap_custom_metric.md).

# @tensorleap\_custom\_metric

code\_loader.inner\_leap\_binder.leapbinder\_decorators.tensorleap\_custom\_metric

The `tensorleap_custom_metric` decorator registers a [**Custom Metric**](https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/custom-metrics.md).

```python
@tensorleap_custom_metric(name='distances',
                          direction=MetricDirection.Downward,
                          compute_insights=None)
def distances(
    tensor_1: npt.NDArray[np.float32],
    tensor_2: npt.NDArray[np.float32],
    ...
) -> Union[npt.NDArray[np.float32], Dict[str, npt.NDArray[np.float32]]]:
    pass
```

| Args               |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`             | *(str)* The name of the metric. Must be unique among metrics.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `direction`        | *(*[*MetricDirection*](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/enums/metricdirection.md) *or Dict\[str,* [*MetricDirection*](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/enums/metricdirection.md)*], optional)* Whether lower (`MetricDirection.Downward`) or higher (`MetricDirection.Upward`) values are better. For a metric that returns a dictionary, pass a dictionary from result key to direction; keys you leave out default to `Downward`. Defaults to `Downward`; leaving it out produces a warning in the local run. |
| `compute_insights` | *(bool or Dict\[str, bool], optional)* Whether the platform computes insights on this metric. `None` (the default) and `True` mean yes; `False` means no. For a metric that returns a dictionary, pass a dictionary from result key to `bool`.                                                                                                                                                                                                                                                                                                                                                  |

#### Function inputs

Any number of `np.ndarray` arguments, each with a batch axis at position 0: ground truths, model predictions or encoded inputs. The integration test call decides which tensor goes to which argument.

One argument may instead be typed [`SamplePreprocessResponse`](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/datasetclasses/samplepreprocessresponse.md) to receive the ids of the samples in the batch.

#### Function output

One value per sample in the batch, in one of these forms:

* a 1-D `np.ndarray`
* a `list` of `float`, `int` or `None`
* a `list` of `list` of [`ConfusionMatrixElement`](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/datasetclasses/confusionmatrixelement.md), for a confusion-matrix metric
* a `dict` from `str` to any of the above, to return several metrics from one function. Each key becomes its own metric.

### Examples

#### Basic Usage

```python
import numpy as np
import numpy.typing as npt
from typing import Dict
from code_loader.contract.enums import MetricDirection
from code_loader.inner_leap_binder.leapbinder_decorators import tensorleap_custom_metric


@tensorleap_custom_metric(name='distances',
                          direction={'mean_difference': MetricDirection.Downward,
                                     'mean_absolute_difference': MetricDirection.Downward})
def distances(y_true: npt.NDArray[np.float32], y_pred: npt.NDArray[np.float32]) -> Dict[str, npt.NDArray[np.float32]]:
    diff = y_true.astype(np.float32) - y_pred.astype(np.float32)
    axis = tuple(range(1, diff.ndim))
    return {
        'mean_difference': np.mean(diff, axis=axis),
        'mean_absolute_difference': np.mean(np.abs(diff), axis=axis),
    }
```

Full script usage can be found at [**Integration Script**](https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code.md#dataset-script).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/decorators/tensorleap_custom_metric.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
