2012-04-13 26 views
0

我有一個函數可以適用於許多不同的數據集,所有數據集都具有相同的點數。例如,我可能想要將多項式擬合到圖像的所有行。有沒有一種有效的,矢量化的方式來做這件事,用scipy或其他包,還是我不得不求助於一個單一的循環(或使用多處理,以加快一點)?在Python中同時擬合N個數據集

回答

0

您可以使用numpy.linalg.lstsq

import numpy as np 

# independent variable 
x = np.arange(100) 

# some sample outputs with random noise 
y1 = 3*x**2 + 2*x + 4 + np.random.randn(100) 
y2 = x**2 - 4*x + 10 + np.random.randn(100) 

# coefficient matrix, where each column corresponds to a term in your function 
# this one is simple quadratic polynomial: 1, x, x**2 
a = np.vstack((np.ones(100), x, x**2)).T 

# result matrix, where each column is one set of outputs 
b = np.vstack((y1, y2)).T 

solutions, residuals, rank, s = np.linalg.lstsq(a, b) 

# each column in solutions is the coefficients of terms 
# for the corresponding output 
for i, solution in enumerate(zip(*solutions),1): 
    print "y%d = %.1f + (%.1f)x + (%.1f)x^2" % ((i,) + solution) 


# outputs: 
# y1 = 4.4 + (2.0)x + (3.0)x^2 
# y2 = 9.8 + (-4.0)x + (1.0)x^2 
+0

謝謝!此方法僅適用於多項式,還是可以將其用於任意函數? – astrofrog 2012-04-13 09:36:12

+0

@astrofrog:你可以放任何功能。例如'a = np.vstack((np.exp(x),x))。T'將嘗試擬合'A * e^x + B * x'。只需相應地構建您的列。 – Avaris 2012-04-13 09:46:15