回归问题:
求最优的w,b
import numpy as np
import pandas as pd
# y = wx + b
def compute_error_for_line_given_points(b,w,points):# 计算损失
totalError = 0
for i in range(len(points)):
x = points[i,0]
y = points[i,1]
totalError += (y - (w*x + b))**2
return totalError / float(len(points))
def step_gradient(b_current,w_current,points,learningRate): # 计算梯度
b_gradient = 0
w_gradient = 0
N = float(len(points))
for i in range(len(points)):
x = points[i,0]
y = points[i,1]
b_gradient += -(2/N)*(y-((w_current*x) + b_current))# 在式子中对b求导,在求平均,
w_gradient += -(2/N) * (y-((w_current*x) + b_current)) * x
new_b = b_current - (learningRate*b_gradient)# 更新新的b,w
new_w = w_current - (learningRate * w_gradient)
return [new_w,n