> 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_loss.md).

# @tensorleap\_custom\_loss

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

The `tensorleap_custom_loss` decorator registers a [**Custom Loss Function**](https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/custom-loss-function.md).

```python
@tensorleap_custom_loss(name='weighted_ce')
def loss(tensor_1: np.ndarray, tensor_2: np.ndarray, ...) -> np.ndarray:
    pass
```

| Args   |                                                            |
| ------ | ---------------------------------------------------------- |
| `name` | *(str)* The name of the loss. Must be unique among losses. |

#### 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

A 1-D `np.ndarray` with one loss value per sample in the batch.

{% hint style="warning" %}
A loss may only use inputs that are also fed to the model. If a loss needs extra data, put it in the ground truth and read it from there.
{% endhint %}

### Examples

#### Basic Usage

```python
import numpy as np
from code_loader.inner_leap_binder.leapbinder_decorators import tensorleap_custom_loss

CLASS_WEIGHTS = np.array([0.5, 2.1, 3, 4, 4, 4, 4, 4], dtype=np.float32)


@tensorleap_custom_loss(name='weighted_ce')
def weighted_categorical_crossentropy(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
    y_true = y_true.astype(np.float32)
    y_pred = y_pred.astype(np.float32)
    y_pred = y_pred / np.sum(y_pred, axis=-1, keepdims=True)
    y_pred = np.clip(y_pred, 1e-7, 1 - 1e-7)
    return -np.sum(y_true * np.log(y_pred) * CLASS_WEIGHTS, axis=-1)
```


---

# 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_loss.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.
