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

一曲冷凌霜 提交于 2019-12-13 01:25:36

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22538655/how-do-i-get-minuit-minuit-to-fit-a-gaussian-curve-to-my-data-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!