fit_polynomial1.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Fit y=ax+b and compute error bands"""
  2. from vedo import Text2D, DashedLine, show
  3. from vedo.pyplot import plot, fit
  4. import numpy as np
  5. # np.random.seed(0)
  6. # Generate some noisy data points along a line
  7. a, b = (np.random.rand(2)-0.5)*10 # choose a and b
  8. x = np.linspace(0, 15, 25)
  9. y = a*x + b
  10. noise = np.random.randn(len(x)) * 5 # create gaussian noise
  11. # Plot the points and add the "true" line without noise
  12. fig = plot(x, y+noise, '*k', title=__doc__, label='data')
  13. fig += DashedLine(x, y).c('red5')
  14. # Fit points and evaluate, with a bootstrap and Monte-Carlo technique,
  15. # the correct error coeffs and error bands. Return a Line object:
  16. pfit = fit(
  17. [x, y+noise],
  18. deg=1, # degree of the polynomial
  19. niter=500, # nr. of MC iterations to compute error bands
  20. nstd=2, # nr. of std deviations to display
  21. )
  22. fig += [pfit, pfit.error_band, *pfit.error_lines] # add these objects to fig
  23. msg = f"Generated a, b : {np.array([a,b])}"\
  24. f"\nFitted a, b : {pfit.coefficients}"\
  25. f"\nerrors on a, b : {pfit.coefficient_errors}"\
  26. f"\nave point spread: :sigma :approx {pfit.data_sigma:.3f} in y units"
  27. msg = Text2D(msg, font='VictorMono', pos='bottom-left', c='red3')
  28. fig.add_label("y = a:dotx+b", c='k', marker='-', mc='red4')
  29. fig.add_label("ground truth", c='k', marker='--', mc='red5')
  30. fig.add_label("1:sigma error band", c='k', marker='s', mc='grey')
  31. fig.add_legend(pos=[1.07,1], vspace=2)
  32. show(fig, msg, zoom=1.1).close()