Handy Python Snippets
1. Converting between NumPy arrays, PyTorch tensors, and images
NumPy array and PIL image
from PIL import Image |
NumPy array and PyTorch tensor
import torch |
PyTorch tensor and PIL image
from PIL import Image |
2. Converting between NumPy arrays and lists
import numpy as np |
How arrays and lists differ
A NumPy array has one dtype. A Python list can hold objects of different types.
import numpy as np |
3. NumPy sum()
With no axis argument, sum() returns the sum of all elements.
axis selects the dimension to reduce.
For a three-dimensional array, axes 0, 1, and 2 count from the outermost dimension to the innermost.
Negative axes count from the end. In a three-dimensional array, -1 is innermost, and -3 is outermost.
The figure illustrates NumPy sum() along different axes.

keepdims retains reduced axes as dimensions of length one.
array([[1],[2]]) |
4. np.linalg.norm()
linalg stands for linear algebra.
Norm
import numpy as np |
x is the input vector or matrix.
ord selects the type of norm.
| ord | Norm type | Formula |
|---|---|---|
| None | L2 norm (default for a vector) | $\sqrt{x_1^2+x_2^2+…+x_n^2}$ |
| 1 | L1 norm | $|x_1|+|x_2|+…+|x_n|$ |
| 2 | L2 norm | $\sqrt{x_1^2+x_2^2+…+x_2^2}$ |
| np.inf | Infinity norm | $max(|x_i|)$ |
axis determines the dimension or dimensions over which the norm is evaluated.
keepdims retains reduced axes as dimensions of length one.