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.
linear_regression(x, y)
x
: This is the independent variable.y
: This is the dependent variable.The method returns the slope
and intercept
.
Let’s look at the code below:
import statisticsx = [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)
statistics
module.x
.y
.slope
and intercept
of x
and y
using the linear_regression()
method.slope
and intercept
value.