[Up]

Levenberg-Marquardt法によるfitting

指数関数でfittingを行う簡単なプログラム。より複雑な最適化プログラムを書く場合のプロトタイプとして使用できる。

import scipy
##from matplotlib import *
import pylab
from scipy.optimize import leastsq
"""
Example of curve fitting for
a1*exp(-k1*t) + a2*exp(-k2*t)
"""
def dbexpl(t,p):
    return(p[0]*pylab.exp(-p[1]*t) + p[2]*pylab.exp(-p[3]*t))

def residuals(p,data,t):
    err = data - dbexpl(t,p)
    return err



a1,a2 = 1.0, 1.0
k1,k2 = 0.05, 0.2
t=scipy.arange(0,100,0.1)
data = dbexpl(t,[a1,k1,a2,k2]) + 0.02*pylab.randn(len(t))
p0 = [0.5,1,0.5,1] # initial guesses
guessfit = dbexpl(t,p0)
pbest = leastsq(residuals,p0,args=(data,t),full_output=1)
bestparams = pbest[0]
cov_x = pbest[1]
print 'best fit parameters ',bestparams
print cov_x
datafit = dbexpl(t,bestparams)
pylab.plot(t,data,'x',t,datafit,'r',t,guessfit)
pylab.xlabel('Time')
pylab.title('Curve-fitting example')
pylab.grid(True)
pylab.draw()
pylab.show()

[Up]