Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. # number of points
  5. num_points = 300
  6.  
  7. # For the sample data
  8. # Input
  9. x = []
  10. # Output
  11. y = []
  12.  
  13. # Answer values
  14. x_ans = [i * 0.01 for i in range(-200, 200)]
  15. W_ans = 0.1
  16.  
  17. # Generate normal random values for input and output
  18. for i in range(num_points):
  19. _x = np.random.normal(0.0, 0.55)
  20. _y = W_ans * _x + np.random.normal(0.0, 0.03)
  21.  
  22. x.append(_x)
  23. y.append(_y)
  24.  
  25. # Draw input, output and answer line
  26. plt.plot(x, y, "ro")
  27. plt.plot(x_ans, [W_ans * _x for _x in x_ans], label="W=0.1")
  28. plt.xlabel("X")
  29. plt.ylabel("Y")
  30. plt.legend()
  31. plt.title("y = 0.1 * x")
  32. plt.show()
  33.  
  34. # For the Mean Square Error
  35. # Weight from 0 to 0.2
  36. W = [i * 0.001 for i in range(0, 200)]
  37. # Cost
  38. cost = []
  39.  
  40. for w in W:
  41. # hypothesis = W * x
  42. hypo = [w * _x for _x in x]
  43. diffSqrt = 0
  44.  
  45. for i in range(num_points):
  46. _hypo = hypo[i]
  47. _y = y[i]
  48.  
  49. # sum((W * x - y)^2)
  50. diffSqrt = diffSqrt + (_hypo - _y)**2
  51.  
  52. # 1 / m * sum(W * x - y)^2
  53. cost.append(1 / (len(W)) * diffSqrt)
  54.  
  55. # Draw cost function
  56. plt.plot(W, cost)
  57. plt.title("Cost Function")
  58. plt.xlabel("W")
  59. plt.ylabel("Cost(W)")
  60. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement