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

Python中如何用scipy调整变量x最小化表格总平方误差

求解最优x最小化总平方误差的实现方案

方法1:使用scipy优化工具求解

你可以通过scipy.optimize.minimize函数迭代求解最优x值,实现代码如下:

from scipy.optimize import minimize
import pandas as pd
import numpy as np    

# 初始化原始数据表
df = pd.DataFrame({
    'Reference Value' : [4.8, 2.4, 3.6, 0.6, 4.8, 5.4], 
    'True Result' : [8, 4, 6, 1, 8, 9]
})

# 定义损失函数:输入x,返回总平方误差
def calc_total_squared_error(x):
    predicted = df['Reference Value'] * x
    return np.sum(np.square(df['True Result'] - predicted))

# 设置初始猜测值为之前使用的1.5,启动优化
optimize_result = minimize(calc_total_squared_error, x0=1.5)

# 提取优化结果
optimal_x = optimize_result.x[0]
min_total_error = optimize_result.fun

print(f"最优x取值:{optimal_x}")
print(f"最小总平方误差:{min_total_error}")

运行代码后输出的最优x约为1.66666667,总平方误差接近0,符合预期的理想状态。

方法2:直接用闭式解计算(无需调用scipy)

该场景属于过原点的一元线性回归问题,存在全局唯一的解析解,不需要迭代优化就可以直接计算出最优x:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Reference Value' : [4.8, 2.4, 3.6, 0.6, 4.8, 5.4], 
    'True Result' : [8, 4, 6, 1, 8, 9]
})

# 直接代入公式计算最优x:sum(xi*yi)/sum(xi^2)
optimal_x = np.sum(df['Reference Value'] * df['True Result']) / np.sum(np.square(df['Reference Value']))
print(f"最优x取值:{optimal_x}")

该方法计算得到的结果和scipy优化结果完全一致,计算效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:45:04