python高斯拟合_将高斯曲线拟合到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)

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.

Edit

Here's the Traceback:

Traceback (most recent call last):

File "F:\Numerical methods\rw893 final assignment.py", line 21, in

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)

解决方案

Probably your callback is called in curve_fit with a different number of parameters.

Have a look at the documentation where it says:

The model function, f(x, ...). It must take the independent variable

as the first argument and the parameters to fit as separate remaining

arguments.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值