Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring