Reputation: 315
If the object function is
How to code it in python?
I've already coded the normal one:
import numpy as np import scipy as sp from scipy.optimize import leastsq import pylab as pl m = 9 #the degree of the polynomial def real_func(x): return np.sin(2*np.pi*x) #sin(2 pi x) def fake_func(p, x): f = np.poly1d(p) #polynomial return f(x) def residuals(p, y, x): return y - fake_func(p, x) #randomly choose 9 points as x x = np.linspace(0, 1, 9) x_show = np.linspace(0, 1, 1000) y0 = real_func(x) #add normalize noise y1 = [np.random.normal(0, 0.1) + y for y in y0] p0 = np.random.randn(m) plsq = leastsq(residuals, p0, args=(y1, x)) print 'Fitting Parameters :', plsq[0] pl.plot(x_show, real_func(x_show), label='real') pl.plot(x_show, fake_func(plsq[0], x_show), label='fitted curve') pl.plot(x, y1, 'bo', label='with noise') pl.legend() pl.show()
Upvotes: 0
Views: 1501
Reputation: 22907
Since the penalization term is also just quadratic, you could just stack it together with thesquares of the error and use weights 1 for data and lambda for the penalization rows.
scipy.optimize.curvefit does weighted least squares, if you don't want to code it yourself.
Upvotes: 0