What is the statistics.linear_regression() method in Python?

Overview

In a linear function, simple linear regression defines the connection between an independent variable x and a dependent variable y.

y = slope * x + intercept

Note: Refer to A deep dive into linear regression to learn more about linear regression.

The linear_regression() method is used to get the slope and intercept of a simple linear regression given the values x and y using the ordinary least squares estimation method. This method was introduced in Python version 3.10.

The inputs x and y should be the same length and should at least have two data points.

Syntax

linear_regression(x, y)

Parameters

  • x: This is the independent variable.
  • y: This is the dependent variable.

Return value

The method returns the slope and intercept.

Code

Let’s look at the code below:

import statistics
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [11 ,13, 12, 15, 17, 18, 18, 19, 20, 22]
slope, intercept = statistics.linear_regression(x, y)
print("Slope - ", slope)
print("Intercept - ", intercept)

Explanation

  • Line 1: We import the statistics module.
  • Line 3: We define the independent variable x.
  • Line 4: We define the dependent variable y.
  • Line 5: We obtain the slope and intercept of x and y using the linear_regression()method.
  • Lines 8 and 9: We print the slope and intercept value.