Python curvefit inside a for loop

Viewed 169

I have a simple linear regression model which I find coefficients using python curve-fit as follows:

import numpy as np
from scipy.optimize import curve_fit

def line(x,m,c):     #linear fit function in order to get the slope
    return m*x + c

x = np.array([2005.38,2005.46,2017.39])
y = np.array([631137.78, 631137.88, 631138.12])

popt, pcov = curve_fit(line,x,y)

slope = popt[0]
intercept = popt[1]
perr = np.sqrt(np.diag(pcov)) 
slope_err = perr[0]
intercept_err = perr_RA[1]

Then I have performed Monte Carlo simulation based on prior and generated about 1000 similar y array as follows however my x array should stay the same. So same x array for all MC generated y arrays:

y = np.array([631137.97960858, 631137.97958298, 631137.97544918]),
 array([631138.00349615, 631138.00462398, 631138.18676081]),
 array([631137.83121579, 631137.83457397, 631138.37689362]),
 array([631138.03276579, 631138.03322997, 631138.10819225]),
 array([631137.79168171, 631137.79288829, 631137.98774176])]

Now, I would like to perform the same calculation and obtain coefficients as I showed above, however, when I put them in a for loop it does not properly calculate coefficients.

nsims = 1000

y = []
slope_mc = []
int_mc = []
for i in range(nsims):
    m = models[i]
    y.append(m[:,0])
    popt, pcov = curve_fit(line,x,m[:,0])
    slope = popt[0]
    intercept = popt[1]
    slope_mc.append(slope)
    int_mc.append(intercept)

I have received an error stating

OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)

I have look at similar solutions like this one but it did not solve my problem. Also is there an easier/faster way without using for loop? I appreciate any help.

0 Answers
Related