Category NumPy

np.linalg.eig: Eigenvalues and Eigenvectors

np.linalg.eig: Eigenvalues and Eigenvectors

A square matrix can be analyzed by finding its eigenvalues and eigenvectors. NumPy’s np.linalg.eig returns the eigenvalues and right eigenvectors, with each vector in the column matched to its value by index. This article shows how to compute eigenpairs with…

How to Use np.sin() in NumPy

np.sin() in NumPy: Radians, Arrays, and Examples

A NumPy calculation may need the sine of one angle or a whole set of angles. The np.sin() function computes sine from radian inputs and applies the calculation element by element to arrays. This article shows how to calculate sine…

np.outer(): Outer Product in NumPy

np.outer(): Outer Product in NumPy

To calculate every pairwise product between two inputs, use NumPy’s np.outer function. It multiplies each value in one input by each value in the other and returns a two-dimensional array. This article explains how the input shapes determine the result…

np.linalg.solve() Linear Systems

np.linalg.solve() Linear Systems

To solve a set of linear equations, find the values of its unknowns. NumPy’s np.linalg.solve() does that when the coefficient matrix has the same number of rows and columns and its equations are independent. I’ll show how to put the…

Python Logarithm Base 2 Using NumPy log2()

Python Logarithm Base 2 Using NumPy log2()

For a set of numbers, you can use a base-2 logarithm to express each value as an exponent on two. NumPy’s log2 function calculates that result element by element for array-like input. This article shows how to apply np.log2 to…

Regression in Python: Fit Models with NumPy

Regression in Python: Fit Models with NumPy

To estimate a numeric target from input values, regression gives you a way to model how those values relate to the target. NumPy’s least-squares routine finds coefficients from arrays, with each coefficient describing how an input value changes the prediction.…

SVD NumPy: Decompose a Matrix

SVD NumPy: Decompose a Matrix

To decompose a matrix in NumPy, use SVD. SVD expresses the matrix as a product of factors. I’ll explain the shapes of those factors and show how to reconstruct the matrix or make a lower-rank approximation. TL;DR: NumPy SVD returns…

NumPy empty and empty_like

NumPy empty and empty_like

When you’re about to fill a NumPy array with your own values straight away, you only need NumPy to set aside the space. np.empty creates that array without setting its values, and np.empty_like does the same using another array’s shape…

Use np.arctan2() for Coordinate Angles

Use np.arctan2() for Coordinate Angles

Given a point’s x and y coordinates, you may need the angle it makes with the x-axis. np.arctan2 calculates that angle and uses the signs of both coordinates to put it in the right quadrant. You’ll get the angle in…