What is the Numpy.linalg.lstsq() Method in Python

Numpy.linalg.lstsq() method is “used to calculate the optimal solution for a given set of data points, making it a valuable tool for data analysis and modeling.”

Syntax

Numpy.linalg.lstsq(a, b, rcond=’warn’)

Parameters

  1. a: It depicts a coefficient matrix.
  2. b: It depicts Ordinate or “dependent variable” values. If the parameter is a two-dimensional matrix, the least square is calculated for each K column of that specific matrix.
  3. Rcond: It is of float datatype. It is a cut-off ratio for smaller singular values of a. In rank determination, singular values are treated as zero if smaller than rcond times a’s largest singular value.

Return Value

  1. X: It depicts the least-squares solution. If the input was a two-dimensional matrix, the solution is always in the K columns of x.
  2. Residuals: It depicts the Sum of residuals or a squared Euclidean 2-norm for each column in b-a*x. If a rank is <N or M<=Nshowspicts an empty array. If b is 1-dimensional, it will be a (1,) shape array. Otherwise, the shape becomes (k,)
  3. Rank: It returns in Int datatype and depicts the rank of matrix A.
  4. S: It depicts the singular values of a.

Note

If b is a matrix, the results are in matrix forms.

Example 1: How to Use numpy.linalg.lstsq() Method

import numpy as np
import matplotlib.pyplot as plt

# x co-ordinates
x = np.arange(0, 9)
A = np.array([x, np.ones(9)])

# linearly generated sequence
y = [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24]

# obtaining the parameters of regression line
w = np.linalg.lstsq(A.T, y, rcond=None)[0]
print(w)

Output

[0.71666667 19.18888889]

Example 2: Plotting the graph

import numpy as np
import matplotlib.pyplot as plt

# x co-ordinates
x = np.arange(0, 9)
A = np.array([x, np.ones(9)])

# linearly generated sequence
y = [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24]

# obtaining the parameters of regression line
w = np.linalg.lstsq(A.T, y, rcond=None)[0]
print(w)

line = w[0]*x + w[1] # regression line
plt.plot(x, line, 'r-')
plt.plot(x, y, 'o')
plt.show()

Output

Numpy linalg lstsq()

Example 3

import numpy as np

# Define the coefficient matrix 'a'
# For a system of equations like:
# 3*x0 + 2*x1 = 9
# x0 + 2*x1 = 8
# The coefficient matrix would be:
a = np.array([[3, 2], [1, 2]])

# Define the ordinate values 'b'
b = np.array([9, 8])

# Use np.linalg.lstsq() to solve for 'x'
x, residuals, rank, s = np.linalg.lstsq(a, b, rcond=None)

print("Solution:", x)

Output

Solution: [0.5 3.75]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.