问题
I am looking for a way to fit parametric equations to a set of data points, using Python.
As a simple example, given is the following set of data points:
import numpy as np
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2, 0, 3, 7, 13])
Using t
as the parameter, I want to fit the following parametric equation to the data points,
t = np.arange(0, 5, 0.1)
x = a1*t + b1
y = a2*t**2 + b2*t + c2
that is, have Python find the values for the coefficients a1
, b1
, a2
, b2
, c2
that fits (x,y)
best to the data points (x_data, y_data)
.
Note that the y(t)
and x(t)
functions above only serve as examples of parametric equations. The actual functions I want to fit my data to are much more complex, and in those functions, it is not trivial to express y
as a function of x
.
Help will be appreciated - thank you!
回答1:
You can use polyfit, but please take care that the length of t must match the length of data points
import numpy as np
tt = np.linspace(0, 5, len(x_data))
x_params = np.polyfit(tt, x_data, 1)
y_params = np.polyfit(tt, y_data, 2)
Change the third parameter to the degree that you think fits your data.
To get the function you can use
y = np.poly1d(y_params)
t = np.arange(0, 5, 0.1)
plot(t, y(t))
plot(tt, y_data, 'o')
回答2:
Since the relation between x
and y
is a quadratic one, you can use np.polyfit
to get the coefficients.
According to your equations, your x
and y
relation is:
y = a2*((x-b1)/a1)**2 + b2*((x-b1)/a1) + c2
Using polyfit, we get
y_data = np.array([2, 0, 3, 7, 13])
x_data = np.array([1, 2, 3, 4, 5])
np.polyfit(x_data,y_data,2)
[p2,p1,p0] = list(array([ 1.21428571, -4.38571429, 4.8 ]))
The values of a1, b1, a2, b2, c2
can be obtained by solving the following eqns
p2 = a2/a1**2
p1 = -2b1*a2/a1**2 + b2/a1
p0 = a2*b1**2/a1**2 -b2*b1/a1 + c2
来源:https://stackoverflow.com/questions/38221050/how-to-fit-parametric-equations-to-data-points-in-python