Skip to content

Commit df47d3f

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 16430ba commit df47d3f

1 file changed

Lines changed: 22 additions & 20 deletions

File tree

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
"""
22
Ordinary Least Squares Regression (OLSR):
33
4-
Ordinary Least Squares Regression (OLSR) is a statistical method for
5-
estimating the parameters of a linear regression model.
6-
It is the most commonly used regression method,
7-
and it is based on the principle of minimizing
4+
Ordinary Least Squares Regression (OLSR) is a statistical method for
5+
estimating the parameters of a linear regression model.
6+
It is the most commonly used regression method,
7+
and it is based on the principle of minimizing
88
the sum of the squared residuals.
99
10-
Below is simple implementation of OLSR
10+
Below is simple implementation of OLSR
1111
without using any external libraries.
1212
1313
WIKI: https://en.wikipedia.org/wiki/Ordinary_least_squares
1414
"""
1515

1616
import numpy as np
1717

18+
1819
def ols_regression(x, y):
19-
"""
20+
"""
2021
Performs Ordinary Least Squares Regression (OLSR) on the given data.
2122
2223
Args:
@@ -35,20 +36,21 @@ def ols_regression(x, y):
3536
0.0
3637
>>> round(b, 2) # Slope should be 2.0
3738
2.0
38-
"""
39+
"""
40+
41+
# Calculate the mean of the independent variable and
42+
# the dependent variable.
43+
x_mean = np.mean(x)
44+
y_mean = np.mean(y)
3945

40-
# Calculate the mean of the independent variable and
41-
# the dependent variable.
42-
x_mean = np.mean(x)
43-
y_mean = np.mean(y)
46+
# Calculate the slope of the regression line.
47+
b = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean) ** 2)
4448

45-
# Calculate the slope of the regression line.
46-
b = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean)**2)
49+
# Calculate the intercept of the regression line.
50+
a = y_mean - b * x_mean
4751

48-
# Calculate the intercept of the regression line.
49-
a = y_mean - b * x_mean
52+
return a, b
5053

51-
return a, b
5254

5355
if __name__ == "__main__":
5456
import doctest
@@ -63,14 +65,14 @@ def ols_regression(x, y):
6365
a, b = ols_regression(x, y)
6466

6567
# Intercept (a) and slope (b) of the regression line
66-
print('Intercept:', a)
67-
print('Slope:', b)
68+
print("Intercept:", a)
69+
print("Slope:", b)
6870

69-
# Predict the target variable for a new data point with
71+
# Predict the target variable for a new data point with
7072
# an independent variable value of 6
7173
x_new = 6
7274

7375
# Make a prediction
7476
y_pred = a + b * x_new
7577

76-
print('Prediction:', y_pred)
78+
print("Prediction:", y_pred)

0 commit comments

Comments
 (0)