선형 회귀 코드 구현

3074 단어 기계 학습
# -*- coding: utf-8 -*-
import numpy as np
import pylab

def Loss(b,m,x,y):
    L1 = (y-m*x-b)**2
    L2 = np.sum(L1,axis = 0)
    return L2
def GD(m,b,learning_rate,x,y,data):
    N = float(len(data))
    for i in range(10000):
        wcost_m = -(2/N) * x * (y - m*x - b)
        wcost_b = -(2/N) * (y - m*x - b)
        weifen_m = np.sum(wcost_m,axis = 0)
        weifen_b = np.sum(wcost_b,axis = 0)
        m = m - weifen_m * learning_rate
        b = b - weifen_b * learning_rate
        if i%1000==0:
            #print m,b
            print Loss(b,m,x,y)
    return [m,b]

def plotfunction(x,y,intial_m,intial_b,learning_rate,data):
    m_ok,b_ok = GD(intial_m,intial_b,learning_rate,x,y,data)
    print m_ok,b_ok
    yhat = m_ok * x + b_ok
    pylab.plot(x,y,'o')
    pylab.plot(x,yhat,'k-')
    pylab.show()
def main():
    intial_m = 0.0;
    intial_b = 0.0;
    learning_rate = 0.001
    data =np.loadtxt('data.csv',delimiter=',')
    x = data[:,0]
    y = data[:,1]
    print x,y
    plotfunction(x,y,intial_m,intial_b,learning_rate,data)

if __name__ == '__main__':
    main()
# :python 
# : 
# : 
# : 
# :for 
# : 
# : 

좋은 웹페이지 즐겨찾기