本文介绍了如何获取minuit.Minuit以使高斯曲线适合Python中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用minuit.Minuit函数使高斯适合一些简单数据,但它不会更改我的任何参数。如果有人可以帮助我,我将非常感激。

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

它吐出错误:
分钟.MinuitError:协方差不是正定的。

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

推荐答案

Minuit是最小化器,但您给了它一个fit函数,而不是给它一个目标函数。 (此函数实际上不是正定的,因此错误消息是适当的。)

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

这不会有效利用您的Numpy数组,但是如果结合了最小化函数和拟合函数,您应该可以通过ufunc来做到这一点。

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旨在提供对拟合技术的更底层访问。如果您只对普通的最小二乘感兴趣,则可能会发现Direct-Minuit界面很麻烦。另一方面,如果您打算通过套索回归约束某些参数,提供非二次甚至非对称损失函数,或者您计划进行甚至无法转化为以下形式的优化:功能合适的话,那么低级接口是有好处的。

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.

这篇关于如何获取minuit.Minuit以使高斯曲线适合Python中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 03:58