Advertisement
Guest User

Untitled

a guest
Jan 26th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. data=np.genfromtxt('artificial.txt', delimiter=',', skip_header=1) # Columns: x, y
  4.  
  5. def generate_poly_features(x, q):
  6. # Generate "design matrix" for the polynomial regression model
  7. # y= θ_0 + θ_1*x + θ_1*x^2 + ... + θ_q*x^q
  8. # The matrix has(q + 1) columns where column i contains elements
  9. # of the vector x raised to the i-th power
  10. X=np.ones(shape=(x.shape[0],q+1))
  11.  
  12. for i in range(0,q+1):
  13. X[:,i] = np.power(x,i)
  14. return X
  15.  
  16. def poly_fit(x, y, q):
  17. # Pre: x and y are 1-dimensional arrays
  18. theta = np.linalg.solve(X.T.dot(x), X.T.dot(y))
  19. return theta
  20.  
  21. def poly_predict(xtest, theta):
  22. ypred=xtest.dot(theta)
  23.  
  24. return ypred
  25.  
  26. # Load data, predict and plot
  27. x=data[:,0]
  28. y=data[:,1]
  29. deg = 3
  30. X=generate_poly_features(x, deg)
  31. theta = poly_fit(X,y,deg)
  32. ypred = poly_predict(X, theta)
  33. plt.plot(x,ypred, color="red")
  34. plt.scatter(x,y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement