File: examples.md

package info (click to toggle)
eagerpy 0.30.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 440 kB
  • sloc: python: 3,914; makefile: 73; javascript: 38; sh: 30
file content (49 lines) | stat: -rw-r--r-- 969 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
---
title: Examples

---

# Examples :tada:

## A framework-agnostic `norm` function

Write your function using EagerPy:

```python
import eagerpy as ep

def norm(x):
    x = ep.astensor(x)
    result = x.square().sum().sqrt()
    return result.raw
```

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**.

```python
import torch
norm(torch.tensor([1., 2., 3.]))
# tensor(3.7417)
```

```python
import tensorflow as tf
norm(tf.constant([1., 2., 3.]))
# <tf.Tensor: shape=(), dtype=float32, numpy=3.7416575>
```

```python
import jax.numpy as np
norm(np.array([1., 2., 3.]))
# DeviceArray(3.7416575, dtype=float32)
```

```python
import numpy as np
norm(np.array([1., 2., 3.]))
# 3.7416573867739413
```

::: tip NOTE
EagerPy already comes with a [builtin implementation of `norm`](/api/norms.md#l2).
:::