如何拟合数据集以便它们共享一些(但不是全部)参数值

时间:2015-06-14 23:49:53

标签: python numpy scipy curve-fitting data-fitting

假设我想要使用指数函数拟合两个数组x_data_oney_data_one。为了做到这一点,我可以使用以下代码(其中x_data_oney_data_one给出虚拟定义):

import numpy as np
from scipy.optimize import curve_fit

def power_law(x, a, b, c):
    return a * (x + c) ** b

x_data_one = np.random.rand(10)
y_data_one = np.random.rand(10)

(a_one, b_one, c_one), _ = curve_fit(power_law, x_data_one, y_data_one)

现在假设我想要拟合第二个数据集:

x_data_two = np.random.rand(10)
y_data_two = np.random.rand(10)

(a_two, b_two, c_two), _ = curve_fit(power_law, x_data_two, y_data_two)

我怎样才能执行这两种情况,以至于他们被约束为a_one == a_twob_one == b_two,但不一定是c_one == c_two?我不想将a_oneb_one限制为特定值;我想找到最适合两个数据集的值。

1 个答案:

答案 0 :(得分:1)

您可以简单地覆盖第二个数据集的函数:

def power_law2(x, c):
    return a_one * (x + c) ** b_one

x_data_two = np.random.rand(10)
y_data_two = np.random.rand(10)

c_two = curve_fit(power_law2, x_data_two, y_data_two)[0][0]

或者你可以使用它(它找到所有数据的最佳a,b,data_one的最佳c1和data_two的c2):

def power_law(x, a, b, c1, c2):
    l = len(x_data_one)
    return a * np.hstack([x[:l] + c1, x[l:] + c2]) ** b

x_data_one_two = np.hstack([x_data_one,x_data_two])
y_data_one_two = np.hstack([y_data_one,y_data_two])

(a_one, b_one, c_one, c_two), _ = curve_fit(power_law, x_data_one_two, y_data_one_two)

在我看来,第二个代码更好更pythonic:)