首页 文章

在Scipy LeastSq中 - 如何添加惩罚词

提问于
浏览
0

如果对象函数是
enter image description here

如何在python中编码?我已编码正常的:
enter image description here

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()

1 回答

  • 0

    由于惩罚项也只是二次方,你可以将它与错误的方形叠加在一起,并使用权重1表示数据,lambda表示惩罚行 .

    如果你不想自己编码,scipy.optimize.curvefit会加权最小二乘法 .

相关问题