scipy.optimize.curve_fit无法拟合偏移的高斯曲线 [英] scipy.optimize.curve_fit unable to fit shifted skewed gaussian curve

查看:171
本文介绍了scipy.optimize.curve_fit无法拟合偏移的高斯曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用scipy的

I am trying to fit a skewed and shifted Gaussian curve using scipy's curve_fit function, but I find that under certain conditions the fitting is quite poor, often giving me close to or exactly a straight line.

下面的代码来自curve_fit文档.提供的代码是用于测试目的的任意数据集,但是很好地显示了问题.

The code below is derived from the curve_fit documentation. The code provided is an arbitrary set of data for test purposes but displays the issue quite well.

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import math as math
import scipy.special as sp

#def func(x, a, b, c):
#    return a*np.exp(-b*x) + c

def func(x, sigmag, mu, alpha, c,a):
    #normal distribution
    normpdf = (1/(sigmag*np.sqrt(2*math.pi)))*np.exp(-(np.power((x-mu),2)/(2*np.power(sigmag,2))))
    normcdf = (0.5*(1+sp.erf((alpha*((x-mu)/sigmag))/(np.sqrt(2)))))
    return 2*a*normpdf*normcdf + c

x = np.linspace(0,100,100)
y = func(x, 10,30, 0,0,1)
yn = y + 0.001*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn,) #p0=(9,35,0,9,1))

y_fit= func(x,popt[0],popt[1],popt[2],popt[3],popt[4])

plt.plot(x,yn)
plt.plot(x,y_fit)

当我将高斯距离零太远时(使用mu),该问题似乎弹出.我尝试给出初始值,甚至那些与我的原始函数相同的值,但它不能解决问题.对于mu=10的值,curve_fit可以很好地工作,但是如果我使用mu>=30,它将不再适合数据.

The issue seems to pop up when I shift the gaussian too far from zero (using mu). I have tried giving initial values, even those identical to my original function, but it does not solve the problem. For a value of mu=10, curve_fit works perfectly, but if I use mu>=30 it not longer fits the data.

推荐答案

提供最小化的起点通常会产生奇迹.尝试给最小化器一些关于最大值的位置和曲线的宽度的信息:

Giving starting points for minimization often works wonders. Try giving the minimizer some information on the position of the maximum and the width of the curve:

popt, pcov = curve_fit(func, x, yn, p0=(1./np.std(yn), np.argmax(yn) ,0,0,1))

使用sigma=10mu=50更改代码中的这一行会产生

Changing this single line in your code with sigma=10 and mu=50 produces

这篇关于scipy.optimize.curve_fit无法拟合偏移的高斯曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆