批梯度下降的 python 实现

来源:互联网 发布:淘宝便宜好吃的零食店 编辑:程序博客网 时间:2024/06/05 02:40
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 02 09:51:35 2015


@author: brian
"""
import numpy as np
if __name__ == "__main__":
    x = []
    y = []
    fx = open('ex2x.dat','r')
    for line in fx:
        x.append(float(line))
    fx.close()
    fy = open('ex2y.dat','r')
    for line in fy:
        y.append(float(line))
    fy.close()
    m = len(y)
    y = np.array(y)
    y.shape = (50,1)
    # Gradient descent
    x = np.array([x])
    x.shape  = (m,1)
    x = np.column_stack([np.ones([m,1]) ,x])
    theta = np.zeros([2,1])
    MAX_ITR = 1500
    alpha = 0.07
    i = 0
    while i < MAX_ITR:
        grad = (float(1)/m) * np.dot(x.T , ( np.dot(x , theta) - y))
        theta = theta - alpha * grad
        i = i+1
    print theta
0 0
原创粉丝点击