如何强制曲线拟合中的特定点

How to force specific points in curve fitting

我想进行曲线拟合,但有限制。

我的数据是从 0-255 值到 0-1 的校准。 我想强制拟合函数通过点 (0,0) 和 (255,1)。

我当前的代码:

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

def model_func(x, a, b, c):    
    return a*(np.exp(x*b)) + c   

if __name__ == "__main__":
    #=== Fit Curve
    x = np.array([0, 20, 56, 65, 110, 122, 168, 179, 202, 203, 210, 211, 217, 220, 221, 223, 240, 255])
    y = np.array([0, 0.015, 0.02, 0.0 , 0.08, 0.08, 0.22, 0.28, 0.43, 0.5, 0.51, 0.64, 0.65, 0.74, 0.82, 0.84, 0.88, 1])
    popt, pcov = curve_fit(model_func, x, y, p0=(0.1 ,1e-3, 0.1))

    #=== Plot
    plt.figure()
    plt.scatter(x, y)
    xdata = np.linspace(0, 255, 1000)
    plt.plot(xdata, model_func(xdata, popt[0], popt[1], popt[2]))
    text = "$f(x)=ae^{b*x}+c$ | a=%.3f, b=%.3f, c=%.3f" % (popt[0],popt[1],popt[2])
    plt.annotate(text, xy=(0.03, 0.95), xycoords='axes fraction', fontsize=12)
    plt.xlim([0,255])
    plt.ylim([0,1])
    plt.grid()

适合以下情况:

this answer类似,我发现最简单的方法是使用sigma参数,为第一个和最后一个点赋予更高的权重。

我添加了这个:

sigma = np.ones(len(x))
sigma[[0, -1]] = 0.01
popt, pcov = curve_fit(model_func, x, y, p0=(0.1 ,1e-3, 0.1), sigma=sigma)

现在我的身材符合我的要求: