简体   繁体   中英

How do I get minuit.Minuit to fit a gaussian curve to my data in Python?

I am trying to fit a gaussian to some simple data using the minuit.Minuit function but it doesnt change any of my parameters. If anyone can help out I would be very grateful.

import numpy as np
import minuit

xCurve = np.array([0,1,2,3,4,5,6,7,8,9])
yCurve = np.array([0,1,2,3,4,5,4,3,2,1])


def Gaus(a,b,c):
    return a*np.exp(-((xCurve-b)**2)/(2*c**2))

m = minuit.Minuit(Gaus,a=4.5,b=5,c=0.4)
m.printMode=1
m.migrad()
m.printMode=0
m.values()

a = m.values['a']
b = m.values['b']
c = m.values['c']
d = m.values['d']
print a
print b
print c
print d

it spits out an error: minuit.MinuitError: Covariance is not positive definite.

Minuit is a minimizer, but you gave it a fit function, rather than an objective function. (This function is literally not positive definite, so the error message is appropriate.)

To get what you actually want, do this:

def gauss(x, a,b,c):
    return a*np.exp(-((x-b)**2/(2*c**2)))

def minimizeMe(a,b,c):
    return sum((gauss(x, a,b,c) - y)**2 for x, y in zip(xCurve, yCurve))

m = minuit.Minuit(minimizeMe, a=4.5, b=5, c=0.4)
m.printMode = 1
m.migrad()

This doesn't make efficient use of your Numpy arrays, but if you combine the minimizer and fit functions, you should be able to do it by ufunc.

PyMinuit is intended to provide more low-level access to the fitting technique. If you're only interested in ordinary least squares, you might find the direct-Minuit interface to be cumbersome. If, on the other hand, you plan to constrain some parameters with lasso regression, provide non-quadratic or even non-symmetric loss functions, or if you're planning to do an optimization that can't even be cast into the form of a function fit, then the low-level interface is a benefit.

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