【线性回归】- 梯度下降法计算线性回归参数

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
1.读取数据
train = np.genfromtxt('data.csv', delimiter=',')

# 提取 train 中的两列数据 作为X , y
X = train[:, 0]
y = train[:, 1]
# 画出散点图
plt.scatter(X, y)
plt.show()

在这里插入图片描述

2.定义损失函数
  • 拟合函数
    在这里插入图片描述
  • 损失函数
    在这里插入图片描述
# 定义损失函数
def loss_function(w, b, train):
    
    total_cost = 0.0
    M = len(train)
    
    # 逐点计算损失函数的值
    for i in range(M):
        x = train[i,0]
        y = train[i,1]
        total_cost += (y - w * x - b) ** 2
    
    return total_cost / (2 * M)
3.定义模型的超参数
alpha = 0.0001 # 学习率
init_w = 0 # 初始的 w 参数值
init_b = 0 # 初始的 b 的参数值
num_iter = 10 # 迭代次数
4.使用梯度下降计算参数
  • 求导公式
    在这里插入图片描述
def grad_desc(train, init_w, init_b, alpha, num_iter):

    w = init_w
    b = init_b

    # 记录下降过程中损失函数的值
    cost_values = []
    
    for i in range(num_iter):
        # 记录下降过程中顺势函数的值
        cost_values.append(loss_function(w, b, train))
        # 梯度下降 注意这个传入的是 w, 和 b
        w, b = setp_grad_desc(train, w, b, alpha)
    
    return [w, b, cost_values]
    
def setp_grad_desc(train, current_w, current_b, alpha):
    
    sum_grad_w = 0 # 对 w 的导数求和
    sum_grad_b = 0 # 对 b 的导数求和
    M = len(train)
    
    # 计算导数和
    for i in range(M):
        x = train[i,0]
        y = train[i,1]
        sum_grad_w += (current_w * x + current_b - y) * x
        sum_grad_b += current_w * x + current_b - y
    # 使用公式计算当前梯度
    grad_w = sum_grad_w / M
    grad_b = sum_grad_b / M 

    # 更新当前 w 和 b的值
    update_w = current_w - alpha * grad_w
    update_b = current_b - alpha * grad_b
    
    return update_w, update_b
    
# 使用梯度下降计算
w, b, cost_values= grad_desc(train, init_w, init_b, alpha, num_iter)

print("w is :" , w)
print("b is :" , b)

# 计算损失函数
cost = loss_function(w, b, train)
print("cost is :" , cost)

# 画出梯度下降的数据图
plt.plot(cost_values)
plt.show()


w is : 1.394730441275591
b is : 0.027713586724842688
cost is : 130.31761996260104

在这里插入图片描述

5.画出拟合曲线
x = train[:,0]
y = train[:,1]
plt.scatter(x, y)
pre_y = w * x + b
plt.plot(x, pre_y , color='r')

在这里插入图片描述

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兀坐晴窗独饮茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值