Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Thursday, August 1, 2024

NumPy Cheatsheet with Examples



 

This includes a cheatsheet-like code with examples for numpy.

To make this work, first install numpy:

pip3 install numpy


Examples:

import numpy as np


def multiply_by_scalars():
print("=== multiply by scalars ===")
x = np.array([1., 2., 3.])
weight = np.array([4., 5., 6.])

print("x", x)
print("weight", weight)

# same as: output = x.dot(weight)
output = x @ weight
print(output)


def multiply_matrix():
print("=== multiply matrix ===")
x = np.ones(([2, 3]), dtype=int)
y = np.ones(([3, 4]), dtype=int)
print(x @ y)

print("transpose to multiply")
print(x @ x.transpose())


def multiple_dimensions_array():
print("=== multiple dimensions array ===")
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D array", array_2d)
print("index access", array_2d[1, 2])


def convert_types():
print("=== convert types ===")
a = np.array([1, 2, 3])

print("before convert")
print("a", a)
print("a type", a.dtype)

print("after convert (better to work with float32 on GPU)")
a = a.astype(np.float32)
print("a", a)
print("a type", a.dtype)


def check_dimensions():
print("=== check dimensions ===")
array_3d = np.array([
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
],
[
[1001, 1002, 1003, 1004],
[1005, 1006, 1007, 1008],
[1009, 10010, 10011, 10012],
],
])
print(array_3d)
print("dimensions", array_3d.ndim)
print("shape", array_3d.shape)


def create_predefined_arrays():
print("=== create predefined arrays ===")

print("ones")
print(np.ones((2, 3), dtype=np.int32))

print("zeros")
print(np.zeros((2, 3), dtype=np.int32))

print("constants")
print(42 + np.zeros((2, 3), dtype=np.int32))

print("I matrix")
print(np.eye(4, dtype=np.int32))

print("diagonal")
print(np.diag((5, 6, 7)))

print("configure range and step size")
print(np.arange(10., 5., -0.5))

print("configure number of elements within range")
print(np.linspace(0., 20., num=4))

print("random arrays")
np.random.seed(42)
print(np.random.rand(3, 2))


def array_slices():
print("=== array slices ===")
a = np.array([[1, 2, 3], [4, 5, 6]])

print("slice by index")
print(a[0])

print("slice from end")
print(a[-1])

print("slice by range")
print(a[1, 0:2])

print("slice by column")
print(a[:, 0])


def array_math():
print("=== array math ===")
a = np.array([[1, 2, 3], [4, 5, 6]])

print(a)

print("add")
print(a + 1)

print("power")
print(a ** 2)

print("sum by rows")
print(np.add.reduce(a, axis=0))

print("sum by columns")
print(np.add.reduce(a, axis=1))

print("max by columns")
print(np.max(a, axis=1))


def broadcast():
print("=== broadcast ===")
a = np.array([[1, 1, 1], [7, 7, 7]])
b = np.array([1, 2, 3])
print(a + b)


def slice_changes_original():
print("=== slice changes original ===")
a = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

print("default slice is a view on the original")
first_row = a[0]
first_row += 1
print(a)

print("using copy() duplicates memory")
second_row = a[1].copy()
second_row += 1
print(a)

print("fancy index (non continuous) always uses a copy")
fancy_slice = a[[0, 2]]
fancy_slice += 100
print(fancy_slice)
print(a)


def boolean_masks():
print("=== boolean masks ===")
a = np.array([[1, 5, 2], [8, 4, 7]])
print(a >= 5)

print("multiple conditions")
complex_condition = (a >= 5) & (a < 8)
print(complex_condition)

print("select only the elements that match a condition (this is fancy condition)")
print(a[complex_condition])

print("check how many elements answer a condition")
print(complex_condition.sum())

print("update by boolean condition")
print(np.where(a >= 5, 100, 55))


def reshape_array():
print("=== reshape array ===")
a = np.random.rand(12)
print(a)

array_2d = a.reshape(3, 4)
print(array_2d)

print("reshape shares the memory of the original")
print(np.may_share_memory(a, array_2d))

print("reshape without knowing one dimension")
print(a.reshape(-1, 6))

print("flatten array")
i = np.eye(3)
# same as: print(i.reshape(-1))
print(i.flatten())

print("create vector")
a = np.array([1, 2, 3])
# same as: print(a.reshape(-1, 1))
# same as: print(a[:, None])
print(a[:, np.newaxis])


def concatenate_array():
print("=== concatenate array ===")
a = np.array([[1, 2, 3], [4, 5, 6]])

print("add rows")
print(np.concatenate((a, a), axis=0))

print("add columns")
print(np.concatenate((a, a), axis=1))


multiply_by_scalars()
multiply_matrix()
multiple_dimensions_array()
convert_types()
check_dimensions()
create_predefined_arrays()
array_slices()
array_math()
broadcast()
slice_changes_original()
boolean_masks()
reshape_array()
concatenate_array()



No comments:

Post a Comment