在Python中同时拟合N个数据集

时间:2012-04-13 08:52:01

标签: python curve-fitting

我有一个功能,我想适应多个不同的数据集,所有数据都具有相同的点数。例如,我可能想要将多项式拟合到图像的所有行。是否有一种有效的和矢量化的方法来使用scipy或其他包,或者我是否必须求助于单个循环(或使用多处理来加快它的速度)?

1 个答案:

答案 0 :(得分: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