Python实现已知部分系数的曲线拟合(二次多项式已知b、c求a)
固定系数多项式拟合的Python实现
二次多项式单参数优化最简方案
你当前的场景仅需优化单个参数a,可以直接使用无截距项的最小二乘解析解,无需调用复杂拟合库,计算效率最高:
import numpy as np # 输入你的数据集 X = np.array([1, 2, 3, 4, 5]) Y = np.array([5.2, 12.1, 22.8, 37.5, 56.2]) # 填入已知的固定系数b、c b_fixed = 2 c_fixed = 1 # 转换变量消去固定项的影响 y_transformed = Y - b_fixed * X - c_fixed x_transformed = X ** 2 # 直接计算最优a(最小二乘解析解) a_opt = np.sum(x_transformed * y_transformed) / np.sum(x_transformed ** 2) # 生成拟合结果 y_fit = a_opt * X**2 + b_fixed * X + c_fixed print(f"最优系数a:{a_opt}")
通用多系数固定多项式拟合方案
如果是更高次多项式、固定任意多个系数的场景(比如你提到的5次多项式拟合需求),可以通过构造设计矩阵调用numpy.linalg.lstsq实现,无需依赖curve_fit类迭代拟合方法:
import numpy as np def polyfit_with_fixed_coeffs(X, Y, degree, fixed_coeffs): """ 带固定系数的多项式拟合工具 参数说明: X: 自变量数组 Y: 因变量数组 degree: 多项式最高次数 fixed_coeffs: 字典,key为系数对应的幂次,value为固定值 例:二次多项式固定b(x^1的系数)和c(x^0的系数),传入{1:2, 0:1} 返回值: 完整多项式系数数组,按幂次从高到低排列,和numpy.polyfit返回格式一致 """ # 计算所有固定项的贡献和 fixed_sum = np.zeros_like(Y) for power, val in fixed_coeffs.items(): fixed_sum += val * (X ** power) # 消去固定项后得到待拟合的Y值 Y_transformed = Y - fixed_sum # 提取所有待求解的自由项幂次,构造设计矩阵 free_powers = [p for p in range(degree+1) if p not in fixed_coeffs] A = np.vstack([X**p for p in free_powers]).T # 最小二乘求解自由系数 coeffs_free, _, _, _ = np.linalg.lstsq(A, Y_transformed, rcond=None) # 组装完整系数 full_coeffs = np.zeros(degree+1) for p, val in fixed_coeffs.items(): full_coeffs[p] = val for idx, p in enumerate(free_powers): full_coeffs[p] = coeffs_free[idx] # 按幂次从高到低返回 return full_coeffs[::-1] # 二次场景测试调用 coeffs = polyfit_with_fixed_coeffs(X, Y, degree=2, fixed_coeffs={1:2, 0:1}) # 返回的coeffs[0]为x²系数a,coeffs[1]为固定的b,coeffs[2]为固定的c
以上方案为解析解,不存在迭代拟合的收敛问题,速度远高于自定义函数的迭代拟合方法,完全适配你无法使用scipy.optimize.curve_fit的需求。
内容的提问来源于stack exchange,提问作者Fred Esch
相关产品推荐
相关产品推荐

