Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created February 20, 2018 06:13
Show Gist options
  • Save komasaru/795e73db8d5da36606e39142bc9b901d to your computer and use it in GitHub Desktop.
Save komasaru/795e73db8d5da36606e39142bc9b901d to your computer and use it in GitHub Desktop.
Python script to compute multiple regression equation with NumPy.
#! /usr/local/bin/python3.6
"""
Computation of a multiple regression with NumPy
"""
import sys
import traceback
import numpy as np
class RegressionMulti:
def reg_multi(self, x, y):
""" Regression line computation
:param list x: list of explanatory variables
:param list y: list of objective variables
:return list [b, a_0, a_1]: b, a_0, a_1 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[0]) != len(y):
print("Argument list size is invalid!")
sys.exit()
for i in range(1, len(x)):
if len(x[0]) != len(x[i]):
print("Argument list size is invalid!")
sys.exit()
e = np.array(x)
o = np.array(y)
e = np.vstack([np.ones(e.shape[1]), e])
return np.linalg.lstsq(e.T, o)[0]
except Exception as e:
raise
if __name__ == '__main__':
try:
x = [
[10, 9, 8, 6, 8, 4, 9, 10, 2, 3, 8, 6, 7, 5],
[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]
for i, a in enumerate(x):
print("説明変数 X{} = {}".format(i + 1, x[i]))
print("目的変数 Y =", y)
print("---")
obj = RegressionMulti()
res = obj.reg_multi(x, y)
print("b =", res[0])
print("a_0 =", res[1])
print("a_1 =", res[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