Linear algebra and functions with NumPy

image credits to eduCBA

The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient low-level implementations of standard linear algebra algorithms.

The Linear Algebra module of NumPy offers various methods to apply linear algebra on any NumPy array.
One can find:

  • rank, determinant, trace, etc. of an array.
  • eigenvalues of matrices
  • matrix and vector products (dot, inner, outer, etc. product), matrix exponentiation
  • solve linear or tensor equations.

The SciPy library also contains a linalg submodule and there is overlap in the functionality provided by the SciPy and NumPy submodules.

Commonly used linalg functions:

diagReturn the diagonal (or off-diagonal) elements of a square matrix as a 1D array, or convert a 1D array into a square matrix with zeros on the off-diagonal

dotMatrix multiplication

traceCompute the sum of the diagonal elements

detCompute the matrix determinant

eigCompute the eigenvalues and eigenvectors of a square matrix

invCompute the inverse of a square matrix

What Is Vectorization?

“Vectorization” (simplified) is the process of rewriting a loop so that instead of processing a single element of an array N times, it processes (say) 4 elements of the array simultaneously N/4 times.It is faster as modern CPUs are optimized for such operations.

So in Numpy, The concept of vectorized operations allows the use of more optimal and pre-compiled functions and mathematical operations on NumPy array objects and data sequences. The Output and Operations will speed up when compared to simple non-vectorized operations.

What are ufuncs?

Ufuncs stands for Universal Functions in Numpy. ufuncs are used to implement vectorization in NumPy which is way faster than iterating over elements.

To create your own ufunc, you have to define a function, as you do with normal functions in Python, then you add it to your NumPy ufunc library with the frompyfunc() method.

The frompyfunc() method takes the following arguments:

  1. function - the name of the function.
  2. inputs - the number of input arguments (arrays).
  3. outputs - the number of output arrays.

Example to create your own ufunc:

Simple Arithmetic ufuncs:
+np.addAddition (e.g., 1 + 1 = 2)

-np.subtractSubtraction (e.g., 3 - 2 = 1)

-np.negativeUnary negation (e.g., -2)

*np.multiplyMultiplication (e.g., 2 * 3 = 6)

/np.divideDivision (e.g., 3 / 2 = 1.5)

//np.floor_divideFloor division (e.g., 3 // 2 = 1)

**np.powerExponentiation (e.g., 2 ** 3 = 8)

%np.modModulus/remainder (e.g., 9 % 4 = 1)

Trigonometric functions:

These functions work on radians, so angles need to be converted to radians by multiplying by pi/180. Only then we can call trigonometric functions. They take an array as input arguments.

sin, cos, tan-compute sine, cosine, and tangent of angles.

arcsin, arccos, arctan calculate inverse sine, cosine, and tangent

hypotcalculate hypotenuse of given right triangle

sinh, cosh, tanh compute hyperbolic sine, cosine, and tangent

arcsinh, arccosh, arctanh compute inverse hyperbolic sine, cosine, and tangent

deg2rad convert degree into radiansrad2degconvert radians into a degree.

Broadcasting and Shape manipulation

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.

If the dimensions of two arrays are dissimilar, element-to-element operations are not possible.

Broadcasting is possible if the following rules are satisfied −

  • Array with smaller ndim than the other is prepended with ‘1’ in its shape.
  • Size in each dimension of the output shape is the maximum of the input sizes in that dimension.
  • An input can be used in calculation if its size in a particular dimension matches the output size or its value is exactly 1.
  • If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

This demonstrates how array b is broadcast to become compatible with a.

Shape Manipulation

Shape manipulation is a technique by which we can manipulate the shape of a NumPy array and then convert the initial array into an array or matrix of the required shape and size. This may include converting a one-dimensional array into a matrix and vice-versa and finding the transpose of the matrix by using different functions of the NumPy module.

Changing shape can be done with the following funcs :

Transpose operations

Boolean Masking

Masking comes up when you want to extract, modify, count, or otherwise manipulate values in an array based on some criterion: for example, you might wish to count all values greater than a certain value, or perhaps remove all outliers that are above some threshold. In NumPy, Boolean masking is often the most efficient way to accomplish these types of tasks.

Example counting rainy days:

Date and Time in Numpy

With the help of numpy.datetime64() method, we can get the date in a NumPy array in a particular format i.e year-month-day by using numpy.datetime64() method.

A curious learner , an engineer by profession , exploring the world through writings