0

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

4

1 回答 1

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
于 2012-04-13T09:32:15.103 回答