2012-04-13 187 views
8

我有一個非常具體的要求,使用6次多項式插值非線性數據。我已經看到numpy/scipy例程(scipy.interpolate.InterpolatedUnivariateSpline),允許插值僅達到5度。6度曲線擬合與numpy/scipy

即使沒有直接的函數來執行此操作,是否有辦法在Excel中複製LINEST線性迴歸算法蟒蛇? LINEST允許6度曲線擬合,但我不想用Excel來計算任何東西,因爲這個計算是一個更大的Python腳本的一部分。

任何幫助,將不勝感激!

回答

17

您可以使用scipy.optimize.curve_fit來適合您想要的任何功能(合理範圍內)到您的數據。此函數的簽名是

curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw) 

,它使用非線性最小二乘法擬合,以適應函數f到數據ydata(xdata)。在你的情況我會嘗試這樣的:

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

def _polynomial(x, *p): 
    """Polynomial fitting function of arbitrary degree.""" 
    poly = 0. 
    for i, n in enumerate(p): 
     poly += n * x**i 
    return poly 

# Define some test data: 
x = numpy.linspace(0., numpy.pi) 
y = numpy.cos(x) + 0.05 * numpy.random.normal(size=len(x)) 

# p0 is the initial guess for the fitting coefficients, set the length 
# of this to be the order of the polynomial you want to fit. Here I 
# have set all the initial guesses to 1., you may have a better idea of 
# what values to expect based on your data. 
p0 = numpy.ones(6,) 

coeff, var_matrix = curve_fit(_polynomial, x, y, p0=p0) 

yfit = [_polynomial(xx, *tuple(coeff)) for xx in x] # I'm sure there is a better 
                # way of doing this 

plt.plot(x, y, label='Test data') 
plt.plot(x, yfit, label='fitted data') 

plt.show() 

這應該給你這樣的:

enter image description here

+0

可以使用'yfit = _polynomial(XX,*係數_)',還注意到,P0應具有至少爲1的長度,爲0度多項式。 – martijnn2008 2016-06-06 20:04:51