2015-11-05 23 views
2

我想要做一個曲線擬合,但有限制。如何在曲線擬合中強制特定點

我的數據是從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() 

提供了以下適合:

Fit plot

+0

這可能是對你有意思:如何做一個多項式擬合與固定點] (http://stackoverflow.com/questions/15191088/how-to-do-a-polynomial-fit-with-fixed-points) – agold

+0

謝謝@agold,與西格瑪的答案幫了我很多! –

回答

5

類似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) 

現在我配合的樣子,我想:

enter image description here