【PyTorch】回归问题代码实战

梯度下降法是优化算法中一种常用的技术,用于通过最小化损失函数来求解模型的最优参数。在线性回归中,目标是通过拟合数据来找到一条最适合的直线。梯度下降法通过迭代地调整模型参数,使得损失函数(通常是均方误差)最小化,从而找到最优的参数。

线性回归的目标是根据输入特征 x 预测输出 y。假设我们有一个输入特征 x 和对应的输出标签 y,线性回归模型可以用以下公式表示:

给定一组数据集, 我们的目标是通过调整权重 和 ​,使得模型的预测值与真实值之间的误差最小。首先对参数进行求梯度:

通过计算梯度,我们知道了损失函数在每个参数方向上的变化趋势。为了最小化损失函数,我们沿着梯度的反方向更新参数。参数更新的公式为:

采用MSE计算损失函数,损失函数为 ,那么更新后的参数为,其中,

计算损失函数:

python 复制代码
def compute_error_for_line_given_points(b,w,points):
    totalError = 0
    for i in range(0, len(points)):
        x = points[i,0]
        y = points[i,1]
        totalError += (y-(w*x+b))**2
    return totalError/float(len(points))

计算梯度值:

python 复制代码
def step_grdient(b_current, w_current, points, learningRate):
    b_gradient = 0
    w_gradient = 0
    N = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        b_gradient += -(2/N) * (y - ((w_current * x) + b_current))
        # 梯度信息多了一个x
        w_gradient += -(2/N) * x * (y - ((w_current * x) + b_current))
    new_b = b_current - (learningRate * b_gradient)
    new_w = w_current - (learningRate * w_gradient)
    return [new_b, new_w]

循环计算梯度:

python 复制代码
def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):
    b = starting_b
    w = starting_w
    for i in range(num_iterations):
        b, w = step_gradient(b, w, np.array(points), learning_rate)
    return [b, w]

进行运行:

python 复制代码
def run():
    points = np.genfromtext("data.csv", delimiter=",")
    learining_rate = 0.0001
    initial_b = 0
    initial_w = 0
    num_iterations = 100
    print("Starting gradient descent at b={0}, w={1},error={2}".format(initial_b, initial_m, compute_errror_for_line_given_points(initial_b, initial_w, points)))
    print("Running......")
    [b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations)
    print("After {0} iterations b = {1}, w = {2}, error = {3}".format(num_iterations, b, m))
    

参考资料:
6.6 回归问题实战6_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1RiDJYmEEU?spm_id_from=333.788.videopod.episodes&vd_source=0dc0c2075537732f2b9a894b24578eed&p=9

相关推荐
happylifetree1 小时前
Python70:核心语法-函数进阶-案例2
python
王中阳Go2 小时前
两个入口答案不一致先别调模型:6 行入口口径对账表(附脚本)
人工智能·后端·python·大语言模型·1024程序员节
BK贝壳2 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
Sakura_j_h_2 小时前
Python 在定时任务里输出 emoji,UnicodeEncodeError 从哪来
开发语言·字符编码·windows·python·定时任务
奇树谦3 小时前
朴素贝叶斯(Naive Bayes)详解
机器学习·1024程序员节
supabc1234 小时前
欧盟电子发票(XRechnung/Peppol/ZUGFeRD)踩坑记:用 Python 不装 Java 跑官方校验规则
xml·python·开源·电子发票·1024程序员节
ZhengEnCi4 小时前
AI Agent工具调用防护层怎么写-一份能直接跑的Python四层拦截实现
python·llm·agent
企业数字化笔记4 小时前
视频人体姿态怎么做三维可视化?2D关键点、深度局限与技术选型
人工智能·算法·音视频
ZhengEnCi4 小时前
AI Agent工具误调用怎么解决-从参数校验到高危二次确认的四层工程防线
python·llm·agent
古希腊掌管代码的神THU4 小时前
为什么DPO中chosen/rejected概率同时下降?
人工智能·深度学习·机器学习·自然语言处理·面试