Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created January 20, 2018 04:36
Show Gist options
  • Save komasaru/83dca9085c29ceb9285a18fac7e15066 to your computer and use it in GitHub Desktop.
Save komasaru/83dca9085c29ceb9285a18fac7e15066 to your computer and use it in GitHub Desktop.
Python script to compute regression curve.
#! /usr/local/bin/python3.6
"""
Computation of a simple linear regression curve
"""
import sys
import traceback
class RegressionCurve:
def reg_curve(self, x, y):
""" Regression line computation
:param list x: 1st list of variables
:param list y: 2nd list of variables
:return list [a, b, c]: a-value, b-value, c-value
"""
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()
n = len(x) # number of items
m_x = sum(x) / n # avg(X)
m_y = sum(y) / n # avg(Y)
m_x2 = sum([a ** 2 for a in x]) / n # avg(X^2)
m_x3 = sum([a ** 3 for a in x]) / n # avg(X^3)
m_x4 = sum([a ** 4 for a in x]) / n # avg(X^4)
m_xy = sum([a * b for a, b in zip(x, y)]) / n # avg(X * Y)
m_x2y = sum([a * a * b for a, b in zip(x, y)]) / n # avg(X^2 * Y)
s_xx = m_x2 - m_x * m_x # Sxx
s_xy = m_xy - m_x * m_y # Sxy
s_xx2 = m_x3 - m_x * m_x2 # Sxx2
s_x2x2 = m_x4 - m_x2 * m_x2 # Sx2x2
s_x2y = m_x2y - m_x2 * m_y # Sx2y
b = s_xy * s_x2x2 - s_x2y * s_xx2
b /= s_xx * s_x2x2 - s_xx2 * s_xx2
c = s_x2y * s_xx - s_xy * s_xx2
c /= s_xx * s_x2x2 - s_xx2 * s_xx2
a = m_y - b * m_x - c * m_x2
return [a, b, c]
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]
x = [83, 71, 64, 69, 69, 64, 68, 59, 81, 91, 57, 65, 58, 62]
y = [183, 168, 171, 178, 176, 172, 165, 158, 183, 182, 163, 175, 164, 175]
print("説明変数 X =", x)
print("目的変数 Y =", y)
print("---")
obj = RegressionCurve()
reg_curve = obj.reg_curve(x, y)
print("a =", reg_curve[0])
print("b =", reg_curve[1])
print("c =", reg_curve[2])
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