fit_bstrp.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/user/bin/env python
  2. # coding=utf-8
  3. """
  4. @author: yannansu
  5. @created at: 20.04.21 21:37
  6. """
  7. import numpy as np
  8. from scipy.optimize import curve_fit
  9. from sklearn.utils import resample as bootstrap
  10. def fit_bstrp(x, y, func, n_bs, p_ci, p0=None):
  11. """
  12. :param x: x values
  13. :param y: y values
  14. :param func: function for curve fitting
  15. :param n_bs: number of bootstrap
  16. :param p_ci: probability interval
  17. :param p0: initial guess on parameters
  18. :return:
  19. """
  20. bs_ypred = np.zeros((n_bs, y.size))
  21. # Bootstrap
  22. for i in range(n_bs):
  23. xi, yi = bootstrap(x, y)
  24. par_i, cov_i = curve_fit(func, xi, yi, p0=p0, maxfev=2000)
  25. bs_ypred[i] = func(x, *par_i)
  26. # CI from bootstrap results
  27. lower, upper = np.quantile(bs_ypred, [(1 - p_ci) / 2, 1 - (1 - p_ci) / 2], axis=0)
  28. params, cov = curve_fit(func, x, y, p0=p0, maxfev=2000)
  29. # Use least square (believe the noise is Gaussian)
  30. # noise = np.std(y - ypred)
  31. # predictions = np.array([np.random.normal(ypred, noise) for j in range(n_bs)])
  32. # lower,upper = np.quantile(predictions, [1 - p_ci, p_ci], axis = 0)
  33. fit = {'params': params,
  34. 'bounds': [lower, upper]}
  35. return fit