如何使用scipy.optimize中的带有来自多个数据集的共享拟合参数的curve_fit?

问题描述 投票:0回答:1

假设我有一个具有多个参数的拟合函数f,例如ab。现在,我想使多个数据集适合此功能,并对所有数据集使用相同的a(共享参数),而每次适合b可以单独使用。

示例:

import numpy as np

# Fit function
def f(x, a, b):
    return a * x + b

# Datasets
x = np.arange(4)
y = np.array([x + a + np.random.normal(0, 0.5, len(x)) for a in range(3)])

因此,我们有4个x值和3个分别具有4个y值的数据集。

python numpy curve-fitting
1个回答
0
投票

执行此操作的一种方法是连接数据集并使用调整后的拟合函数。

在以下示例中,此操作在带有g的新拟合函数np.concatenate中发生。还完成了每个数据集的个体拟合,因此我们可以将它们的图与具有共享参数的串联拟合进行比较。

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit


# Create example datasets

x = np.arange(4)
y = np.array([x + a + np.random.normal(0, 0.5, len(x)) for a in range(3)])
print("x =", x)
print("y =", y)


# Individual fits to each dataset

def f(x, a, b):
    return a * x + b

for y_i in y:
    (a, b), _ = curve_fit(f, x, y_i)
    plt.plot(x, f(x, a, b), label=f"{a:.1f}x{b:+.1f}")
    plt.plot(x, y_i, linestyle="", marker="x", color=plt.gca().lines[-1].get_color())

plt.legend()
plt.show()


# Fit to concatenated dataset with shared parameter

def g(x, a, b_1, b_2, b_3):
    return np.concatenate((f(x, a, b_1), f(x, a, b_2), f(x, a, b_3)))

(a, *b), _ = curve_fit(g, x, y.ravel())
for b_i, y_i in zip(b, y):
    plt.plot(x, f(x, a, b_i), label=f"{a:.1f}x{b_i:+.1f}")
    plt.plot(x, y_i, linestyle="", marker="x", color=plt.gca().lines[-1].get_color())

plt.legend()
plt.show()

输出:

x = [0 1 2 3]
y = [[0.40162683 0.65320576 1.92549698 2.9759299 ]
 [1.15804251 1.69973973 3.24986941 3.25735249]
 [1.97214167 2.60206217 3.93789235 6.04590999]]

a的三个不同值分别适合:

Figure 1

具有共享参数a的适合:

Figure 2

© www.soinside.com 2019 - 2024. All rights reserved.