使用python语言实现线性回归算法

使用python语言实现线性回归算法:

x = [[1,2.1],[1,2.5],[1,3.9],[1,5.1],[1,2.7]]
y = [4.2,5.1,7.75,10.18,5.35]

theta = [5,1]
threshould = 0.01
alpha = 0.001

def calculateLoss(theta, x, y):
    loss =0

    for i in range (len(y)):
        hypothesis = 0
        for j in range(len(theta)):
            hypothesis += theta[j] *x[i][j]
        loss += (hypothesis - y[i])**2
    return  loss /2 /len(y)

def calculateTheta(theta, x, y, alpha):
    newtheta = [0,0]
    for thetaj in range(len(theta)):
        sum =0
        for i in range(len(y)):
            hypothesis = 0
            for j in range(len(theta)):

                hypothesis += theta[j] * x[i][j]

            sum += (hypothesis-y[i]) * x[i][thetaj]

        step = sum / len (y) * alpha
        newtheta[thetaj] = theta[thetaj] - step
    return newtheta


def gradientDescent(theta, x, y, alpha, threshould):

    while True:

     #判断是否满足要求

        if calculateLoss(theta, x, y) < threshould:
             return theta
    # 计算出一组新的thete
        theta = calculateTheta(theta, x, y, alpha)
# 如果不满足要求,则再次进入循环
# res = gradientDescent(theta, x, y, alpha, threshould)
#
# print (res)
if __name__=="__main__":
    res = gradientDescent(theta, x, y, alpha, threshould)

    print(res)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值