Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import sys
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib import cm
  5. from mpl_toolkits.mplot3d import Axes3D
  6.  
  7. # Parameters
  8. args = sys.argv
  9. argerr = "Please run with arguments: (r alpha | j)"
  10. if len(args) < 2:
  11. print(argerr)
  12. sys.exit()
  13.  
  14. mode = args[1] # r | j
  15. if mode not in ['r', 'j']:
  16. print(argerr)
  17. sys.exit()
  18.  
  19. # Training data
  20. fileX = 'ex2x.dat'
  21. fileY = 'ex2y.dat'
  22. xsFile = open(fileX, 'r')
  23. ysFile = open(fileY, 'r')
  24.  
  25. def loadNums(f, delim):
  26. return [ tuple(float(x) for x in line.strip().split(delim)) for line in f.read().splitlines() ]
  27.  
  28. xs = [ np.array((1,) + xss) for xss in loadNums(xsFile, " ") ]
  29. ys = [ y[0] for y in loadNums(ysFile, " ") ]
  30.  
  31. m = len(xs)
  32. theta = np.array([ 0 for x in xs[0] ])
  33.  
  34. # Helpers
  35.  
  36. def ht(t, x):
  37. return np.dot(t, x)
  38.  
  39. def h(x):
  40. return ht(theta, x)
  41.  
  42. def err(t, x, y):
  43. return ht(t, x) - y
  44.  
  45. def J(t):
  46. return (1.0/(2*m)) * sum([ err(t,x,y)**2 for x, y in zip(xs, ys) ])
  47.  
  48. def delta():
  49. return sum([ (h(x) - y) * x for x, y in zip(xs, ys) ])
  50.  
  51. def gradDescStep():
  52. return theta - (a / m) * delta()
  53.  
  54. def infer(t):
  55. return [ ht(t, x) for x in xs ]
  56.  
  57. # Modes
  58.  
  59. def regression(params):
  60. global theta
  61.  
  62. t0 = theta
  63. t1 = gradDescStep()
  64. for i in range(100):
  65. theta = gradDescStep()
  66. t100 = theta
  67. for i in range(1400):
  68. theta = gradDescStep()
  69. t1500 = theta
  70.  
  71. print("1st iteration: ", t1) # [ 0.07452802 0.38002167]
  72. print("1500th iteration: ", t1500) # [ 0.75015039, 0.06388338]
  73.  
  74. xAxis = [x[1] for x in xs]
  75. plt.suptitle("Linear Regression Demo")
  76. plt.plot(xAxis, ys, "bo", label="data")
  77. plt.plot(xAxis, infer(t0), "y", label="initial")
  78. plt.plot(xAxis, infer(t1), "r", label="1 iteration")
  79. plt.plot(xAxis, infer(t100), "b", label="100 iterations")
  80. plt.plot(xAxis, infer(t1500), "g", label="1500 iterations")
  81.  
  82. plt.axis([1, 9, -.1, 2])
  83. plt.legend()
  84.  
  85. def Jplot():
  86. theta0_vals = np.arange(-2, 3, (5 / 50.0))
  87. theta1_vals = np.arange(-1, 1, (2 / 50.0))
  88. lt0 = len(theta0_vals)
  89. lt1 = len(theta1_vals)
  90. J_vals = [ [0 for j in range(lt1)] for i in range(lt0) ]
  91. for i in range(lt0):
  92. for j in range(lt1):
  93. t = [theta0_vals[i], theta1_vals[j]]
  94. J_vals[i][j] = J(t)
  95.  
  96. X, Y = np.meshgrid(theta0_vals, theta1_vals)
  97.  
  98. fig = plt.figure()
  99. fig.suptitle("J(theta) plot")
  100. ax = fig.add_subplot(111, projection='3d')
  101. ax.plot_surface(X, Y, J_vals, color='r', cmap=cm.coolwarm)
  102.  
  103. if mode == 'r':
  104. if len(args) < 3:
  105. print(argerr)
  106. sys.exit()
  107. else:
  108. a = float(args[2]) # 0.07
  109. regression(a)
  110. else:
  111. Jplot()
  112.  
  113. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement