Disclaimer: this course is adapted from the work by Nicolas Rougier: https://github.com/rougier/numpy-tutorial.
Let us start with a preliminary remark concerning the random part. One is expected to run a command like
import numpy as np
= np.random.default_rng(12) rng
before anything, to initialize the random generator rng
.
Matrix creation
Creation: vector case
Code | Result |
---|---|
x = np.zeros(9) |
|
x = np.ones(9) |
|
x = np.full(9, 0.5) |
|
x = np.zeros(9) x[2] = 1 |
|
x = np.arange(9) |
|
x[::-1] |
|
x = rng.random(9) |
Creation: matrix case
Code | Result |
---|---|
M = np.zeros((5, 9)) |
|
M = np.ones((5, 9)) |
|
M = np.zeros((5, 9)) M[0, 2] = 0.5 M[1, 0] = 1. M[2, 1] = 0.4 |
|
M = np.arange(45).reshape((5, 9)) |
|
M = rng.random((5, 9)) |
|
M = np.eye(5, 9) |
|
M = np.diag(np.arange(5)) |
|
M = np.diag(np.arange(3), k=2) |
|
Meshgrid (🇫🇷: maillage)
= (8, 3)
nx, ny = np.linspace(0, 1, nx)
x = np.linspace(0, 1, ny)
y = np.meshgrid(x, y) xx, yy
x | y | xx | yy |
---|---|---|---|
Creation: tensor cases
Code | Result |
---|---|
T = np.zeros((3, 5, 9)) |
|
T = np.ones((3, 5, 9)) |
|
T = np.arange(135).reshape(3, 5, 9) |
|
T = rng.random((3, rows, cols)) |
|
|
Matrix reshaping
We start here with
= np.zeros((3, 4))
M 2, 2] = 1 M[
Starting from the previous matrix, we can reshape it in different ways:
Code | Result |
---|---|
M = M.reshape(4, 3) |
|
M = M.reshape(12, 1) |
|
M = M.reshape(1, 12) |
|
M = M.reshape(6, 2) |
|
M = M.reshape(2, 6) |
Slicing
Start from a zero matrix:
= np.zeros((5, 9)) M
Starting from the previous matrix, we can slice it in different ways:
Code | Result |
---|---|
M[...] = 1 |
|
M[:, ::2] = 1 |
|
M[::2, :] = 1 |
|
M[1, 1] = 1 |
|
M[:, 0] = 1 |
|
M[0, :] = 1 |
|
M[2:; 2:] = 1 |
|
M[:-2:, :-2] = 1 |
|
M[2:4, 2:4] = 1 |
|
M[::2, ::2] = 1 |
|
M[3::2, 3::2] = 1 |
Operations on matrices
Start from a simple matrix:
= 3, 6
rows, cols = np.linspace(0, 1, rows * cols).reshape(rows, cols) M
Starting from the previous matrix, we can apply the following operations:
Code | Result |
---|---|
M.T |
|
M[::-1, :] |
|
M[:, ::-1] |
|
np.where(M > 0.5, 0, 1) |
|
np.maximum(M, 0.5) |
|
np.minimum(M, 0.5) |
|
np.mean(M, axis=0) |
|
np.mean(M, axis=1) |
|
For the last operations note that the dimensions of the matrices are reduced, so you create a vector as a result, with dimensions (6,)
or (3,)
respectively, when computing the mean along the 0-axis (column-wise mean), respectively along the 1-axis (row-wise mean).
Broadcasting
Broadcasting allows the addition of matrices of different sizes (though this is mathematically wrong), by repeating the smaller ones along the missing dimensions. The only requirement is that the trailing (i.e, rightmost) dimensions match, somehow.
M | N | M+N |
---|---|---|
|
||
|
||
|
|
Resources
- This work is deeply inspired and adapted from the great work by Nicolas Rougier: https://github.com/rougier/numpy-tutorial