Advertisement
Dzham

Untitled

Apr 3rd, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. from IPython.display import clear_output
  2.  
  3. f_true = lambda x: 2*x*np.sin(5*x) + x**2 - 1 # this is the true function
  4.  
  5. # We need this to make the plot of f_true:
  6. x_grid = np.linspace(-2,5,100) # 100 linearly spaced numbers
  7. x_grid_enl = np.hstack((x_grid.reshape((100,1))**j for j in range(6)))
  8. y_grid = f_true(x_grid)
  9.  
  10. A = np.dot(x_grid_enl.T, x_grid_enl)
  11. B = np.dot((x_grid_enl).T, y_grid)
  12.  
  13. for i in range(200):
  14. x_new = np.random.uniform(-2, 5)
  15. y_new = f_true(x_new) + 2*np.random.randn()
  16. p = [x_new**j for j in range(6)]
  17. for l in range(len(A)):
  18. for j in range(len(A)):
  19. A[j,l] += p[l] * p[j]
  20. for l in range(len(B)):
  21. B[l] += p[l] * y_new
  22.  
  23. koeff = np.dot(np.linalg.inv(A), B)
  24. # the rest of code is just bells and whistles
  25. if (i+1)%5==0:
  26. clear_output(True)
  27. plt.plot(x_grid,y_grid, color='blue', label='true f')
  28. plt.scatter(x_new, y_new, color='red')
  29.  
  30. y_pred = [koeff[0] + koeff[1] * (i) + koeff[2] * (i**2) + koeff[3] * (i**3) +
  31. koeff[4] * (i**4) + koeff[5] * (i**5) for i in x_grid]
  32.  
  33. plt.scatter(x_grid, y_pred, color='orange', linewidth=5, label='predicted f')
  34.  
  35. plt.legend(loc='upper left')
  36. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement