diff = X[:, None, :] - X[None, :, :]
D = np.sum(diff**2, axis=-1)
X[:, None, :]
has shape (2, 1, 3)
X[None, :, :]
has shape (1, 2, 3)
(2, 2, 3)
.[i, j, :]
slice contains a = np.arange(6)
a.reshape((2, 3))
a.flatten() # copy
a.ravel() # view
a.T # transpose
Add dimensions:
a[:, np.newaxis]
np.expand_dims(a, axis=0)
Create a matrix and a vector
A = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
A few possible methods:
np.dot(A, b) # dot
A @ A # matrix mult
np.linalg.inv(A) # inverse
np.linalg.solve(A, b)
NumPy ≠ full linear algebra library, but covers essentials.
If you need reproductibility:
np.random.seed(0)
There a several random generation methods:
np.random.rand(2, 3) # uniform [0,1)
np.random.randn(3) # normal
np.random.integers(1, 10, (2, 2))
np.random.choice([1, 2, 3], size=5)
Let
a = np.array([1, 2])
b = np.array([4, 6])
dist = np.linalg.norm(a - b)
Let
Pick a random matrix
X = np.array([[1, 2], [3, 4]])
Compute norm along the column axis
row_norms = np.linalg.norm(X, axis=1, keepdims=True)
X_normed = X / row_norms
We sample points uniformly in the unit square
The probability of falling inside the quarter unit circle is
N = 10000
x = np.random.rand(N)
y = np.random.rand(N)
inside = x**2 + y**2 <= 1
pi_est = 4 * np.sum(inside) / N
NumPy is the foundation of many scientific stacks in Python.
Use the quickstart and examples to learn.
The reference is best when you need details about a function.