lesson3.pdf
    lesson4.pdf

    1. import numpy as np
    2. # y = wx + b
    3. def compute_error_for_line_given_points(b, w, points):
    4. totalError = 0
    5. for i in range(0, len(points)):
    6. x = points[i, 0]
    7. y = points[i, 1]
    8. totalError += (y - (w * x + b)) ** 2
    9. return totalError / float(len(points))
    10. def step_gradient(b_current, w_current, points, learningRate):
    11. b_gradient = 0
    12. w_gradient = 0
    13. N = float(len(points))
    14. for i in range(0, len(points)):
    15. x = points[i, 0]
    16. y = points[i, 1]
    17. b_gradient += -(2/N) * (y - ((w_current * x) + b_current))
    18. w_gradient += -(2/N) * x * (y - ((w_current * x) + b_current))
    19. new_b = b_current - (learningRate * b_gradient)
    20. new_m = w_current - (learningRate * w_gradient)
    21. return [new_b, new_m]
    22. def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):
    23. b = starting_b
    24. m = starting_m
    25. for i in range(num_iterations):
    26. b, m = step_gradient(b, m, np.array(points), learning_rate)
    27. return [b, m]
    28. def run():
    29. points = np.genfromtxt("data.csv", delimiter=",")
    30. learning_rate = 0.0001
    31. initial_b = 0 # initial y-intercept guess
    32. initial_m = 0 # initial slope guess
    33. num_iterations = 1000
    34. print("Starting gradient descent at b = {0}, m = {1}, error = {2}"
    35. .format(initial_b, initial_m,
    36. compute_error_for_line_given_points(initial_b, initial_m, points))
    37. )
    38. print("Running...")
    39. [b, m] = gradient_descent_runner(points, initial_b, initial_m, learning_rate, num_iterations)
    40. print("After {0} iterations b = {1}, m = {2}, error = {3}".
    41. format(num_iterations, b, m,
    42. compute_error_for_line_given_points(b, m, points))
    43. )
    44. if __name__ == '__main__':
    45. run()

    data.csv