【问题标题】:How to use curve_fit from scipy.optimize with a shared fit parameter across multiple datasets?如何使用 scipy.optimize 中的 curve_fit 和跨多个数据集的共享拟合参数?
【发布时间】:2020-02-14 18:10:15
【问题描述】:

假设我有一个带有多个参数的拟合函数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】:

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

    在以下示例中,这发生在新的拟合函数 gnp.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 的三个不同值:

    适合共享参数a

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2013-12-18
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多