python - How do I repeat a for loop while maintaining values from the previous for loop? -
i have written function gradient descent , stuck on figuring out how repeat loop "iters" times. x 2d array , y 2d array. y target value , x data corresponds target value. want iterate through both simultaneously hence zip() in loop, want able repeat iterating through x , y updated coefficients.
i tried wrapping loop in while loop, error saying zip argument #2 must support iteration. i'm assuming happening once loop iterates through 2 ndarrays, compiler cannot "reset" , loop through arrays again. correct , how fix this?
def gradient_descent_lr(x,y,alpha,iters): x_coef = 0 y_int = 0 coef_list = [] x, y in zip(x,y): #evaluate func (0 first) f_eval = (x_coef * x) + y_int #find error error = f_eval - y #update coefficients y_int = y_int - (alpha*error) #adjust bias coefficient error x_coef = x_coef - (alpha*error*x) coef_list.append((float(y_int),float(x_coef))) return coef_list
edit:
nevermind, figured out problem wasn't in iterations, problem in having variable name being y in both argument , in loop. can close question.
[after edit] x , y 2d arrays. x contains x values , y contains y values. why 2d? why not 1d, both n elements. sure that's correct (the 2d mean)? i'd expect them vectors rather matrices. or arrays matrices contain row or column vectors?
also note used y rather y, prevent confusion, since there's y!
also, apart code problems, don't recognize gradient descent in code, may limited knowledge.
def gradient_descent_lr(x,y,alpha,iters): x_coef = 0 y_int = 0 coef_list = [] x, y in zip (x.tolist (), y.tolist ()): #evaluate func (0 first) f_eval = (x_coef * x) + y_int #find error error = f_eval - y #update coefficients y_int = y_int - (alpha*error) #adjust bias coefficient error x_coef = x_coef - (alpha*error*x) coef_list.append((float(y_int),float(x_coef))) return coef_list
Comments
Post a Comment