I have the following code which functions correctly. However, instead of using the method curve_fit, I want to perform the fitting manually using scipy.optimize.minimze on each element. Is it possible and how can we do so?
Here is my code
import numpy as np
import matplotlib.pyplot as plt
import pylab as plb
from scipy.optimize import curve_fit
data = np.loadtxt('gaussian.dat')
x = data[:, 0]
y = data[:, 1]
n = len(x)
mean = sum(x*y)/n
sigma = sum(y*(x-mean)**2)/n
def gauss(x,a,x0,sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gauss,x,y,p0=[1,mean,sigma])
def get_conf_gaus(x: float,popt: np.ndarray, pcov: np.ndarray, n_boostrap:int = 100):
params = np.random.multivariate_normal(popt, pcov, size = [n_boostrap])
a = params[:,0]
mu = params[:,1]
sigma = params[:,2]
bootstrap_y = gauss(0.2,a,mu,sigma)
conf = np.quantile(bootstrap_y, [0.025,0.975])
return conf
conf = get_conf_gaus(0.2, popt, pcov)
print(conf)
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gauss(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Gaussian Fit vs Actual Data')
plt.xlabel('x-values')
plt.ylabel('y-values')
plt.show()