梯度下降法求解线性回归

哎呀呀,

import math

import numpy as np

from matplotlib import pyplot
a=[150,200,250,300,350,400,600]#面积
p=[6450,7450,8450,9450,11450,15450,18450]#价格

ste=0.000000001#步长

ans1=300
ans2=1
m=7

temp1=0
temp2=0
k=0

b1=1
b2=0

while math.fabs(ans1-temp1)>0.0000001 and math.fabs(ans2-temp2)>0.0000001:#当参数ans1与真实值相差小于0.0000001
# while math.fabs(b1-b2)>0.0001:
    sum = 0                                                               #并且参数ans2与真实值相差也小于0.0000001时结束迭代
    k+=1
    for i in range(0, 7):
        sum += ans1 + ans2 * a[i] - p[i]
    sum /= m


    sum1=0
    for i in range(0, 7):
        sum1 += (ans1 + ans2 * a[i] - p[i])*a[i]
    sum1 /= m



    temp2 = ans2

    ans1 = ans1 - sum * ste  # 生成新的ans1
    ans2 = ans2 - sum1* ste  # 生成新的ans2

    b2 = b1
    for i in range(0,7):
        b1=( ans1 +ans2 * a[i] -p[i])**2
    b1/=(2*m)



    print(k)


print(k,ans1,ans2);#输出参数ans1与参数ans2
#打印图形
pyplot.scatter(a, p)
x = np.arange(100, 700, 100)
y = ans2 * x + ans1
pyplot.plot(x, y)
pyplot.xlabel('area')
pyplot.ylabel('price')
pyplot.show()

 不想写代码解释了,直接上图

 

 

 

展开阅读全文

没有更多推荐了,返回首页