-
-
Save fayimora/0d30e91af182b8b811c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def stochastic_linear_gradient_descent(X, y, theta, alpha, tolerance): | |
converged = False | |
prev_cost = 0 | |
n_samples = X.shape[0] | |
while not converged: | |
# use xrange so you dont have to generate the entire range of numbers | |
for i in xrange(n_samples): | |
# you have to sample x and y together | |
# FYI, using one example at a time can be super slow. | |
# you might want to consider using batches which should converge quicker | |
sample_x, sample_y = X[i,:], y[i,:] | |
hypothesis = np.dot(sample_x, theta) | |
loss = hypothesis - sample_y # not sure why you need this | |
# IMHO, it's better to have this function return the cost and gradient | |
# simply because the grad is a partial derivative of the cost w.r.t theta | |
curr_cost, grad = compute_lin_cost(theta, sample_x, sample_y) | |
theta -= alpha * grad | |
# this is wayyyy cleaner that if statements :P | |
converged = abs(curr_cost - prev_cost) < tolerance | |
prev_cost = curr_cost | |
print("cost " , curr_cost) | |
return theta | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment