You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从零实现Linear Regression模型预测结果异常问题求助

线性回归模型错误修复方案

核心问题分析

你的代码存在三个关键错误:

  • 参数初始化错误:线性回归的斜率m和截距b是单个标量参数,而非与样本数量相同的数组。你用np.ones(n)初始化,导致每个样本对应独立的m和b,完全违背线性回归的单一线性假设。
  • 梯度下降计算错误:
    • 更新m时,梯度应为(1/n) * np.sum((h - y) * x),而非(x/n) * np.sum(h - y),后者会将整体误差和与每个x相乘,得到数组而非标量,无法正确更新标量m。
    • 更新b时,梯度与x无关,应为(1/n) * np.sum(h - y),但你复用了同一个grad_des函数,错误地将x代入计算,导致b的更新逻辑完全错误。
  • 假设函数错误:当m和b是数组时,x*m + b会做逐元素运算,而非单一线性预测。

修复后的代码

import numpy as np

x = [10, 15, 23, 30, 40, 49, 57, 60]
y = [10000, 21000, 25000, 30000, 45000, 52000, 65000, 70000]

x = np.array(x)
y = np.array(y)

n = len(x)
# 初始化单个标量参数
m = 1.0
b = 1.0

def hypothesis(x, m, b):
    # 单一线性预测,对所有样本使用相同的m和b
    h = x * m + b
    return h

def cost(y, h):
    c = (1/(2*n)) * np.sum(np.square(h - y))
    return c

# 分开处理m和b的梯度更新,避免复用错误
def update_m(x, y, h, m, L):
    grad_m = (1/n) * np.sum((h - y) * x)
    m = m - L * grad_m
    return m

def update_b(y, h, b, L):
    grad_b = (1/n) * np.sum(h - y)
    b = b - L * grad_b
    return b

iterations = 100000
learning_rate = 0.0005  # 适当调大学习率,加快收敛
for i in range(iterations):
    h = hypothesis(x, m, b)
    c = cost(y, h)
    m = update_m(x, y, h, m, learning_rate)
    b = update_b(y, h, b, learning_rate)
    if i % 10000 == 0:
        print(f"迭代次数: {i}, 损失值: {c:.2f}, m: {m:.2f}, b: {b:.2f}")

# 测试预测
test_x = np.array([10, 15])
test_h = hypothesis(test_x, m, b)
print(f"测试输入{test_x}的预测值: {test_h}")

验证说明

修复后,模型会正确收敛到符合数据的线性参数。对于你提到的简单数据集x=[10,15], y=[20,30],模型最终会学到m=2,b=0,输出正确的预测值[20,30]。

内容的提问来源于stack exchange,提问作者rasul12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:18:20