This can be done by numpy.linalg.lstsq . To explain how to use it, it may be easiest to show how you will do standard 2-nd polyphoring “manually”. Assuming you have your dimension vectors xand y, you first create a so-called design matrix M as follows:
M = np.column_stack((x**2, x, np.ones_like(x)))
after which you can get the usual coefficients as the least square solution to the equation M * k = yusing lstsqas follows:
k, _, _, _ = np.linalg.lstsq(M, y)
k - [a, b, c] . , lstsq , . , y , . , , 2D- z = a * x + b * y (., , , Matlab), , .
, x**2. :
import numpy as np
import matplotlib.pylab as plt
x = np.arange(1000)
y = 0.0001234 * x**2 + 3*np.random.randn(len(x))
M = np.column_stack((x**2,))
k, _, _, _ = np.linalg.lstsq(M, y)
plt.plot(x, y, '.', x, k*x**2, 'r', linewidth=3)
plt.legend(('measurement', 'fit'), loc=2)
plt.title('best fit: y = {:.8f} * x**2'.format(k[0]))
plt.show()
:
