Numpy.polyfit with adapted options

Regarding this: the parameters of the polynomial equation where I get 3 parameters for a quadratic function y = a*x² + b*x + c, now I only want to get the first parameter for the quadratic function that describes my function y = a*x². In other words: I want to set b=c=0and get the adapted parameter for a. In case I understand this correctly, polyphyte cannot do this.

+4
source share
2 answers

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

# generate some noisy data
x = np.arange(1000)
y = 0.0001234 * x**2 + 3*np.random.randn(len(x))

# do fit
M = np.column_stack((x**2,)) # construct design matrix
k, _, _, _ = np.linalg.lstsq(M, y) # least-square fit of M * k = y

# quick plot
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()

: enter image description here

+7

, , . , . , y = 33*x²:

In [51]: x=np.arange(20)

In [52]: y=33*x**2  #y = 33*x²

In [53]: coeffs=np.polyfit(x, y, 2)

In [54]: coeffs
Out[54]: array([  3.30000000e+01,   8.99625199e-14,  -7.62430619e-13])

In [55]: epsilon=np.finfo(np.float32).eps

In [56]: coeffs[np.abs(coeffs)<epsilon]=0

In [57]: coeffs
Out[57]: array([ 33.,   0.,   0.])
-1

Source: https://habr.com/ru/post/1529638/


All Articles