回帰直線をPythonとMatplotlibで描く

2つのリストの要素から回帰直線を導出して、MatplotlibでプロットするプログラムをPythonで書いてみた。たぶんへんてこなプログラムだと思うけど、気にしない。



※ 追記

sum = 0
lst = [1, 2, 3]
for i in lst: sum += i

のようなことやってるけど、sum(lst)でよかったね。

from pylab import *

def meanList(lst):
    """ return the mean of lst """
    sum = 0.0
    for i in lst: sum += i  
    return sum / len(lst)
    
def a_slope(X,  Y):
    """ X, Y : List 
    return a of regression equation y = ax + b """
    L,  s1,  s2 = len(X),  0.0,  0.0
    for i in range(L):
        s1 += X[i] * Y[i]
        s2 += X[i]**2
    return (s1 - L * meanList(X) * meanList(Y))  /  (s2 - L * meanList(X)**2)
    
def b_intercept(X,  Y):
    """ X, Y : List
     return b of regression equation y = ax + b """
    return meanList(Y) - a_slope(X,  Y) * meanList(X)
    
def reg_line(X,  Y):
    """ X, Y : List """
    print "y=", a_slope(X,  Y), "x+(", b_intercept(X,  Y), ")"
    t = arange(0.0, 16.0, 0.1)
    plot(X, Y, 'ro', t,  a_slope(X, Y) * t + b_intercept(X, Y),  'b')
    show()


meanList(lst)はList型のlstの中身の数字の平均を返す。
a_slope(X,Y)とb_interceptは回帰方程式、


y=ax+b
a=\begin{eqnarray}\frac{\sum x_{i}y_{i} - n\bar{x}\bar{y}}{\sum x^{2} - n\bar{x}^{2}}\end{eqnarray}
b=\bar{y} - a\bar{x}
のaとbに対応する。


例)

>>> x = [2.8,	3.4,3.6,5.8,7.0,9.5,10.2,12.3,13.2,13.4]
>>> y = [0.6,	3.0,0.4,1.5,15.0,13.4,7.6,19.8,18.3,18.9]
>>> reg_line(x,y) // 関数を実行
y= 1.74398204288 x+( -4.31113418819 ) // ここでグラフが表示される


プログラムを書くのは久しぶりだー。