-
Notifications
You must be signed in to change notification settings - Fork 0
Tutorial: numpy_utils
This tutorial provides an overview of the functionality provided by numpy_utils
through practical examples. The library contains various utilities for working with NumPy arrays, focusing on reshaping, transformations, and mathematical operations.
Purpose:
Determine the sign of a value or an array of values.
Usage:
import numpy as np
from numpy_utils import sign
print(sign(-10)) # Output: -1
print(sign(0)) # Output: 0
print(sign(10)) # Output: 1
# Vectorized operation
array = np.array([-10, 0, 10])
print(sign(array)) # Output: array([-1, 0, 1])
Purpose:
Get the number of rows or columns in a NumPy array.
Usage:
from numpy_utils import nrow, ncol
array = np.array([[1, 2, 3], [4, 5, 6]])
print(nrow(array)) # Output: 2
print(ncol(array)) # Output: 3
Purpose:
Create a single-row or single-column NumPy array.
Usage:
from numpy_utils import row, col
row_array = row(1, 2, 3)
col_array = col(1, 2, 3)
print(row_array) # Output: array([[1, 2, 3]])
print(col_array) # Output: array([[1], [2], [3]])
Purpose:
Reshape an array to 1D or 2D, respectively.
Usage:
from numpy_utils import to_ndim_1, to_ndim_2
array = [[1, 2], [3, 4]]
print(to_ndim_1(array)) # Output: array([1, 2, 3, 4])
print(to_ndim_2(array)) # Output: array([[1, 2], [3, 4]])
Purpose:
Create matrices, rows, or columns filled with values.
Usage:
from numpy_utils import matrix_of, row_of, col_of
matrix = matrix_of(2, 3, 42) # Create a 2x3 matrix filled with 42
print(matrix)
# Output:
# array([[42, 42, 42],
# [42, 42, 42]])
Purpose:
Make a NumPy array immutable or create an immutable copy of an array.
Usage:
from numpy_utils import make_immutable, immutable_copy_of
array = np.array([1, 2, 3])
immutable_array = make_immutable(array)
copy = immutable_copy_of(array)
print(immutable_array) # Output: array([1, 2, 3])
# Attempting to modify will raise an error
# immutable_array[0] = 5 # Raises ValueError
Purpose:
Compute the Kronecker product or the Kronecker sum of arrays.
Usage:
from numpy_utils import kron, kron_sum
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
kronecker_product = kron(array1, array2)
kronecker_sum = kron_sum(array1, array2)
print(kronecker_product)
# Output:
# array([[ 5, 6, 10, 12],
# [ 7, 8, 14, 16],
# [15, 18, 20, 24],
# [21, 24, 28, 32]])
print(kronecker_sum)
# Output will be a matrix representing the sum of the Kronecker products.
Purpose:
Flatten a matrix into a vector or reshape a vector back into a matrix.
Usage:
from numpy_utils import vec, unvec
matrix = np.array([[1, 2], [3, 4]])
vector = vec(matrix)
print(vector) # Output: array([1, 3, 2, 4])
reshaped_matrix = unvec(vector, 2)
print(reshaped_matrix)
# Output:
# array([[1, 2],
# [3, 4]])
This concludes the numpy_utils
tutorial. For more details, refer to the documentation.