简体   繁体   中英

How to do weighted curve fitting with constraints under python?

I need to do a curve fitting with constraints and weights. reading around, mostly here, I created a function

 def residuals_ga(self,p,h,n,err,kkind=None):

        # checking if to use the minimum or maximum value of kappa
        if kkind == "min":
            kappa = self.k0[0] - self.k0[1]
        elif kkind == "max":
            kappa = self.k0[0] + self.k0[1]
        # checking if kappa is in bounds
        elif p[0] > self.k0[0] + self.k0[1]:
            return float("inf")
        elif p[0] < self.k0[0] - self.k0[1]: 
            return float("inf")
        else:
            kappa = p[0]
        ag = float(p[1])
        hq = lambda n,kappa,ag: self.hq_func(n,1,kappa,ag)
        return (hq(n,kappa,ag) - h)/err**2

From what I gather, this should work. The results, however, are very bad. Is this method right? Did I miss anything?

I should mention that I tested the function itself using xmgrace and it works fine.

Seeing how you are calling this routine might help, as would definitions of self.k0 and self.hq_func.

What is the purpose of

    hq = lambda n,kappa,ag: self.hq_func(n,1,kappa,ag)
    return (hq(n,kappa,ag) - h)/err**2

as opposed to

    return (self.hq_func(n, 1, kappa, ag) - h)/err**2

?

In general, there are many potential cases for which a change in the value for p[0] will change the residual. That makes it hard to determine the derivatives, which is likely to cause unstable results. Returning Inf would definitely cause trouble.

If the idea is to put upper and/or lower bounds on the value a parameter may take, you may find the lmfit package ( http://lmfit.github.io/lmfit-py/ ) helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM