0
我有一个函数可以适用于许多不同的数据集,所有数据集都具有相同的点数。例如,我可能想要将多项式拟合到图像的所有行。有没有一种有效的,矢量化的方式来做这件事,用scipy或其他包,还是我不得不求助于一个单一的循环(或使用多处理,以加快一点)?在Python中同时拟合N个数据集
我有一个函数可以适用于许多不同的数据集,所有数据集都具有相同的点数。例如,我可能想要将多项式拟合到图像的所有行。有没有一种有效的,矢量化的方式来做这件事,用scipy或其他包,还是我不得不求助于一个单一的循环(或使用多处理,以加快一点)?在Python中同时拟合N个数据集
您可以使用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
谢谢!此方法仅适用于多项式,还是可以将其用于任意函数? – astrofrog 2012-04-13 09:36:12
@astrofrog:你可以放任何功能。例如'a = np.vstack((np.exp(x),x))。T'将尝试拟合'A * e^x + B * x'。只需相应地构建您的列。 – Avaris 2012-04-13 09:46:15