| 1 |
--- |
| 2 |
title: Examples |
| 3 |
|
| 4 |
--- |
| 5 |
|
| 6 |
# Examples :tada: |
| 7 |
|
| 8 |
## A framework-agnostic `norm` function |
| 9 |
|
| 10 |
Write your function using EagerPy: |
| 11 |
|
| 12 |
```python |
| 13 |
import eagerpy as ep |
| 14 |
|
| 15 |
def norm(x): |
| 16 |
x = ep.astensor(x) |
| 17 |
result = x.square().sum().sqrt() |
| 18 |
return result.raw |
| 19 |
``` |
| 20 |
|
| 21 |
You can now **use** the `norm` function **with native tensors** and arrays from PyTorch, TensorFlow, JAX and NumPy with **virtually no overhead compared to native code**. Of course, it also works with **GPU tensors**. |
| 22 |
|
| 23 |
```python |
| 24 |
import torch |
| 25 |
norm(torch.tensor([1., 2., 3.])) |
| 26 |
# tensor(3.7417) |
| 27 |
``` |
| 28 |
|
| 29 |
```python |
| 30 |
import tensorflow as tf |
| 31 |
norm(tf.constant([1., 2., 3.])) |
| 32 |
# <tf.Tensor: shape=(), dtype=float32, numpy=3.7416575> |
| 33 |
``` |
| 34 |
|
| 35 |
```python |
| 36 |
import jax.numpy as np |
| 37 |
norm(np.array([1., 2., 3.])) |
| 38 |
# DeviceArray(3.7416575, dtype=float32) |
| 39 |
``` |
| 40 |
|
| 41 |
```python |
| 42 |
import numpy as np |
| 43 |
norm(np.array([1., 2., 3.])) |
| 44 |
# 3.7416573867739413 |
| 45 |
``` |
| 46 |
|
| 47 |
::: tip NOTE |
| 48 |
EagerPy already comes with a [builtin implementation of `norm`](/api/norms.md#l2). |
| 49 |
::: |