Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute regression line.
#! /usr/local/bin/python3.6
"""
Computation of a simple lenear regression line
"""
import sys
import traceback
class RegressionLine:
def reg_line(self, x, y):
""" Regression line computation
:param list x: 1st list of variables
:param list y: 2nd list of variables
:return list [a, b]: a = intercept, b = slope
"""
try:
if type(x) != list:
print("Argument(X) is not a list!")
sys.exit()
if type(y) != list:
print("Argument(Y) is not a list!")
sys.exit()
if len(x) == 0:
print("List(X) is none!")
sys.exit()
if len(y) == 0:
print("List(Y) is none!")
sys.exit()
if len(x) != len(y):
print("Argument list size is invalid!")
sys.exit()
sum_x, sum_y = sum(x), sum(y)
sum_xx = sum([a * a for a in x])
sum_xy = sum([a * b for a, b in zip(x, y)])
a = sum_xx * sum_y - sum_xy * sum_x
a /= len(x) * sum_xx - sum_x * sum_x
b = len(x) * sum_xy - sum_x * sum_y
b /= len(x) * sum_xx - sum_x * sum_x
return [a, b]
except Exception as e:
raise
if __name__ == '__main__':
try:
x = [107, 336, 233, 82, 61, 378, 129, 313, 142, 428]
y = [286, 851, 589, 389, 158, 1037, 463, 563, 372, 1020]
print("説明変数 X =", x)
print("目的変数 Y =", y)
print("---")
obj = RegressionLine()
reg_line = obj.reg_line(x, y)
print("切片 a =", reg_line[0])
print("傾き b =", reg_line[1])
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.