$ M $ order curve $ y = a_mx ^ m + a_ {m-1} x ^ {passing $ n $ points $ (x_1, y_1), \ cdots, (x_n, y_n) $ on the 2D plane I want to find the coefficient $ a_0, \ dots, a_m $ of m-1} + \ cdots + a_1x + a_0 $. If $ n \ le m + 1 $ and the values of $ x_1, \ cdots, x_n $ are all different, there is a curve that passes through all the points, but if not, the coefficient that minimizes the error between the points and the curve. Need to take. At that time, it seems that scipy's fmin method can be used. However, note that the fmin function may not be the optimal solution because it finds the local optimal solution of the objective function.
import numpy as np
from scipy.optimize import fmin
def f(a, x):
#Cubic curve
return a[0] + a[1]*x + a[2]*x**2 + a[3]*x**3
def obj_func(a,x,y):
#The objective function is the sum of the squared errors of the vertices and the curve.
return sum((f(a,x) - y)**2)
#Give 5 points
x = np.array([ -8., -3., 2., 6., 9.])
y = np.array([ 30., -22., 15., -17., -25.])
#Initial value of coefficient
a= np.array([ 0., 0., 0., 0.])
#Find the optimum coefficient
opt = fmin(obj_func, a, args=(x,y))
print(opt)
# [-8.20775435 3.2028276 0.2150416 -0.09395258]
Recommended Posts