为了账号安全,请及时绑定邮箱和手机立即绑定

如何执行多条曲线的联合拟合(在 Python 中)?

如何执行多条曲线的联合拟合(在 Python 中)?

神不在的星期二 2021-09-14 15:54:47
假设我通过简单的线性回归拟合一些数据点。现在我想对几组数据点执行几个联合线性回归。更具体地说,我希望所有拟合中的一个参数相等,此处示意性地描绘了 y 轴交点。在谷歌搜索了一段时间后,我既找不到任何 Python (Scipy) 例程可以做到这一点,也找不到任何一般文献,说明如何实现这一点。理想情况下,我不仅要在简单线性回归的情况下执行这些联合拟合,而且还要针对更一般的拟合函数(例如,幂律拟合与联合指数)。
查看完整描述

2 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

我认为这个图形代码示例可以满足您的需求,使用单个共享参数拟合两个数据集。请注意,如果数据集的长度不等,则可以有效地加权对具有更多单个点的数据集的拟合。此示例将初始参数值显式设置为 1,0 - curve_fit() 默认值 - 并且不使用 scipy 的遗传算法来帮助查找初始参数估计值。


import numpy as np

import matplotlib

import matplotlib.pyplot as plt

from scipy.optimize import curve_fit


y1 = np.array([ 16.00,  18.42,  20.84,  23.26])

y2 = np.array([-20.00, -25.50, -31.00, -36.50, -42.00])

comboY = np.append(y1, y2)


x1 = np.array([5.0, 6.1, 7.2, 8.3])

x2 = np.array([15.0, 16.1, 17.2, 18.3, 19.4])

comboX = np.append(x1, x2)


if len(y1) != len(x1):

    raise(Exception('Unequal x1 and y1 data length'))

if len(y2) != len(x2):

    raise(Exception('Unequal x2 and y2 data length'))



def function1(data, a, b, c): # not all parameters are used here, c is shared

        return a * data + c


def function2(data, a, b, c): # not all parameters are used here, c is shared

        return b * data + c



def combinedFunction(comboData, a, b, c):

    # single data reference passed in, extract separate data

    extract1 = comboData[:len(x1)] # first data

    extract2 = comboData[len(x1):] # second data


    result1 = function1(extract1, a, b, c)

    result2 = function2(extract2, a, b, c)


    return np.append(result1, result2)



# some initial parameter values

initialParameters = np.array([1.0, 1.0, 1.0])


# curve fit the combined data to the combined function

fittedParameters, pcov = curve_fit(combinedFunction, comboX, comboY, initialParameters)


# values for display of fitted function

a, b, c = fittedParameters


y_fit_1 = function1(x1, a, b, c) # first data set, first equation

y_fit_2 = function2(x2, a, b, c) # second data set, second equation


plt.plot(comboX, comboY, 'D') # plot the raw data

plt.plot(x1, y_fit_1) # plot the equation using the fitted parameters

plt.plot(x2, y_fit_2) # plot the equation using the fitted parameters

plt.show()


print('a, b, c:', fittedParameters)



查看完整回答
反对 回复 2021-09-14
  • 2 回答
  • 0 关注
  • 641 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信