梯度下降法实验1

import matplotlib.pyplot as plt
import sys
import numpy as np
x1=np.array([2104,1600,2400,1416,3000])
x2=np.array([3,3,3,2,4])
y=np.array([400,330,369,232,540])
e0=0.01
th0=1
th1=1
th2=1
j=0
alpho=0.01

def hy(xx1,xx2):
    return th0+th1*xx1+th2*xx2 
# th0=th0-(hy(x1[0],x2[0])-y[0])*alpho*1e-1
# print(th0)
# print(hy(x1[0],x2[0])-y[0])

# th0=th0-(hy(x1[0],x2[0])-y[0])*alpho*1e-3
# print((hy(x1[0],x2[0])-y[0])*alpho*1e-3)
# print(th0)
# th1=th1-(hy(x1[0],x2[0])-y[0])*x1[0]*alpho*1e-6
# print((hy(x1[0],x2[0])-y[0])*x1[0]*alpho*1e-6)
# print(th1)
# th2=th2-(hy(x1[0],x2[0])-y[0])*x2[0]*alpho*1e-3
# print((hy(x1[0],x2[0])-y[0])*x2[0]*alpho*1e-3)
# print(th2)
# while (abs(hy(x1[0],x2[0])-y[0])>e0 and abs(hy(x1[0],x2[0])-y[0])*x1[0]>e0 and abs(hy(x1[0],x2[0])-y[0])*x2[0])>e0:
j=0
while(j<20000000):
        th0=th0-(hy(x1[j%4],x2[j%4])-y[j%4])*alpho*1e-2
        th1=th1-(hy(x1[j%4],x2[j%4])-y[j%4])*x1[j%4]*alpho*1e-5
        th2=th2-(hy(x1[j%4],x2[j%4])-y[j%4])*x2[j%4]*alpho*1e-2
        
        if(abs(hy(x1[j%4],x2[j%4])-y[j%4])<e0 and abs((hy(x1[j%4],x2[j%4])-y[j%4])*x1[j%4])<e0 and abs((hy(x1[j%4],x2[j%4])-y[j%4])*x2[j%4])<e0):
            print("true")
            print(hy(x1[j%4],x2[j%4])-y[j%4])
            print(abs((hy(x1[j%4],x2[j%4])-y[j%4])*x1[j%4]))
            print(abs((hy(x1[j%4],x2[j%4])-y[j%4])*x2[j%4]))
            print(th0,th1,th2)
        j=j+1
print("a")
print((hy(x1[0],x2[0])-y[0]))
print(th0,th1,th2)

可行结果
在这里插入图片描述
代入结果验证
在这里插入图片描述
验证结果和y值相近
y=400,330,369,232,540

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值