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

使用Linear Regression预测x/y值遇异常:已知y预测x结果错误

线性回归已知y预测x结果异常的问题排查与解决

问题根源

你在predict_value_y函数里犯了核心逻辑错误:直接用x预测y的回归模型,把y值当成x代入原方程计算x。

原回归方程是为y = slope*x + intercept(从x算y)设计的,你错误执行了predicted = slope*y + intercept,完全违背从y反推x的数学逻辑,自然得到离谱的负数结果。

两种修复方案

方案1:基于原模型参数变形计算

把原回归方程变形,从y = slope*x + intercept推导出x = (y - intercept)/slope,新增计算x的函数:

def place_y(x, slope, intercept):
    return slope * x + intercept

def place_x(y, slope, intercept):
    # 对原方程变形,从y反推x
    return (y - intercept) / slope

def predict_value_x():
    from scipy import stats
    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_err = stats.linregress(age_x, speed_y)
    predict_value = int(input("Given (x) predict (y): \nx = "))
    predicted = place_y(predict_value, slope, intercept)
    print(predicted)

def predict_value_y():
    from scipy import stats
    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_err = stats.linregress(age_x, speed_y)
    predict_value = int(input("Given (y) predict (x): \ny = "))
    # 使用变形后的函数计算x
    predicted = place_x(predict_value, slope, intercept)
    print(predicted)

# 调用测试
predict_value_x()
predict_value_y()

方案2:重新训练y→x的回归模型(更严谨)

x对y的回归和y对x的回归是两条不同直线(仅当相关系数为±1时重合),更严谨的做法是交换自变量和因变量,重新训练模型:

def place_y(x, slope, intercept):
    return slope * x + intercept

def predict_value_x():
    from scipy import stats
    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_err = stats.linregress(age_x, speed_y)
    predict_value = int(input("Given (x) predict (y): \nx = "))
    predicted = place_y(predict_value, slope, intercept)
    print(predicted)

def predict_value_y():
    from scipy import stats
    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    # 交换自变量和因变量,训练y→x的回归模型
    slope_yx, intercept_yx, r, p, std_err = stats.linregress(speed_y, age_x)
    # 此时回归方程为x = slope_yx * y + intercept_yx
    predict_value = int(input("Given (y) predict (x): \ny = "))
    predicted = slope_yx * predict_value + intercept_yx
    print(predicted)

# 调用测试
predict_value_x()
predict_value_y()

测试验证

输入y=85时,两种方案都会得到约10.3的合理结果,而非之前的负数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:52:40