简体   繁体   中英

Not able to replicate curve fitting of a gaussian function in python using curve_fit()

I am trying to fit a Gaussian function to my dataset using scipy's curve_fit() function and have failed to get the function to fit. I tried the same using some other tools like Matlab and the function readily fits. Could someone please help me out here? I am not sure what I am doing wrong. Thanks a lot for any help:)

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

x_data = [12, 34, 56]
y_data = [1e-10, 1e-3, 1e-10]

def func(xdata, a, b, c): 
    return a*np.exp(-(xdata - b)**2/(2*c**2))

popt,_ = curve_fit(func, x_data, y_data)

x_fit = np.linspace(0,100, 100)
y_fit = func(x_fit, *popt)

plt.scatter(x_data, y_data)
plt.plot(x_fit,y_fit)
plt.show()

The above is the code I have tried and I get a bell-curve that is refusing to move from mean point of 0 (the bell part is over x=0).

It fits fine so long as you give it sane initial conditions:

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

x_data = [12, 34, 56]
y_data = [1e-10, 1e-3, 1e-10]


def func(xdata: np.ndarray, a: float, b: float, c: float) -> np.ndarray:
    return a*np.exp(-(xdata - b)**2/(2*c**2))


popt, _ = curve_fit(f=func, xdata=x_data, ydata=y_data, p0=[1e-3, 34, 10])
print(popt)

x_fit = np.linspace(0, 100, 100)
y_fit = func(x_fit, *popt)

plt.scatter(x_data, y_data)
plt.plot(x_fit,y_fit)
plt.show()
[1.00000000e-03 3.40000000e+01 3.87481363e+00]

合身

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM