将高斯曲线拟合到python中的数据 [英] Fitting Gaussian curve to data in python

查看:691
本文介绍了将高斯曲线拟合到python中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拟合高斯曲线并将其绘制到某些给定数据上.这是我到目前为止所拥有的:

I'm trying to fit and plot a Gaussian curve to some given data. This is what I have so far:

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

# Generate data
mu, sigma = 0, 0.1
y, xe  = np.histogram(np.random.normal(mu, sigma, 1000))
x = .5 * (xe[:-1] + xe[1:])

def gauss (x, y):
    p = [x0, y0, sigma]
    return p[0] * np.exp(-(x-p[1])**2 / (2 * p[2]**2))

p0 = [1., 1., 1.]

fit = curve_fit(gauss, x, y, p0=p0)
plt.plot(gauss(x, y))
plt.show()

运行代码时出现此错误:

When I run the code I get this error:

TypeError: gauss() takes exactly 2 arguments (4 given)

我不明白我在哪里给我的函数4个参数.我也不确定我是否正确使用了曲线功能,但是我不确定自己做错了什么.任何帮助将不胜感激.

I don't understand where I have given my function 4 arguments. I'm also not convinced I'm using the curve function correctly, but I'm not sure exactly what I'm doing wrong. Any help would be appreciated.

这是回溯:

Traceback (most recent call last):
  File "F:\Numerical methods\rw893  final assignment.py", line 21, in <module>
    fitE, fitI = curve_fit(gauss, x, y, p0=p0)
  File "F:\Portable Python 2.7.5.1\App\lib\site-packages\scipy\optimize\minpack.py", line 515, in curve_fit
    res = leastsq(func, p0, args=args, full_output=1, **kw)
  File "F:\Portable Python 2.7.5.1\App\lib\site-packages\scipy\optimize\minpack.py", line 354, in leastsq
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
  File "F:\Portable Python 2.7.5.1\App\lib\site-packages\scipy\optimize\minpack.py", line 17, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
  File "F:\Portable Python 2.7.5.1\App\lib\site-packages\scipy\optimize\minpack.py", line 427, in _general_function
    return function(xdata, *params) - ydata
TypeError: gauss() takes exactly 2 arguments (4 given)

推荐答案

可能在curve_fit中使用不同数量的参数调用了您的回调. 看看文档上面写着:

Probably your callback is called in curve_fit with a different number of parameters. Have a look at the documentation where it says:

模型函数f(x,...).它必须采用自变量 作为第一个参数,参数适合作为单独的剩余参数 争论.

The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

为确保能解决此问题,您可能希望在第一个参数之后输入*args并查看获得的结果.

To make sure this works out you might want to take *args after the first argument and have a look at what you get.

这篇关于将高斯曲线拟合到python中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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