解法1:


In [1]:
def regressionLine(x, y):
    """ Return the a (intercept)
        and b (slope) of Regression Line 
        (Y on X).
    """
    import numpy as np
    n = len(x)
    a = np.sum(np.power(x, 2)) * np.sum(y) - np.sum(x) * np.sum(np.multiply(x, y))
    b = n * np.sum(np.multiply(x, y)) - np.sum(x) * np.sum(y)
    c = n * np.sum(np.power(x, 2)) - np.sum(x) ** 2
    return (a / c).round(decimals=4), (b / c).round(decimals=4) 

print(regressionLine([25,30,35,40,45,50], [78,70,65,58,48,42]))
print(regressionLine([56,42,72,36,63,47,55,49,38,42,68,60], [147,125,160,118,149,128,150,145,115,140,152,155]))


(114.381, -1.4457)
(80.777699999999996, 1.1379999999999999)

解法2:


In [2]:
def regressionLine(x, y):
    """ Return the a (intercept)
        and b (slope) of Regression Line 
        (Y on X).
    """
    import numpy as np
    b, a = np.polyfit(x, y, 1)
    return (a.round(decimals=4) , b.round(decimals=4))

print(regressionLine([25,30,35,40,45,50], [78,70,65,58,48,42]))
print(regressionLine([56,42,72,36,63,47,55,49,38,42,68,60], [147,125,160,118,149,128,150,145,115,140,152,155]))


(114.381, -1.4457)
(80.777699999999996, 1.1379999999999999)