user3002486
user3002486

Reputation: 421

How do I repeat a for loop while maintaining values from the previous for loop?

I have written a function for gradient descent and am stuck on figuring out how to repeat the for loop "iters" times. X is a 2d array and y is a 2d array. y is the target value and X is the data that corresponds to the target value. I want to iterate through both simultaneously hence the zip() in the for loop, but I also want to be able to repeat iterating through X and y but with the updated coefficients.

I tried wrapping the for loop in a while loop, but I get an error saying that the zip argument #2 must support iteration. I'm assuming that what is happening is that once the for loop iterates through the 2 ndarrays, the compiler cannot "reset" and loop through the arrays again. Am I correct and how do I fix this?

def gradient_descent_lr(X,y,alpha,iters):
    x_coef = 0
    y_int = 0
    coef_list = []

    for 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 by the error
        x_coef = x_coef - (alpha*error*x)
        coef_list.append((float(y_int),float(x_coef)))

return coef_list

EDIT:

Nevermind, I figured out that the problem wasn't in iterations, the problem was in having the variable name being y in both the argument and in the for loop. You can close this question.

Upvotes: 0

Views: 70

Answers (1)

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

[After your edit] You say X and y are 2D arrays. But you also say X contains your x values and y contains your y values. Why are they 2D? Why not 1D, both with n elements. Are you sure that's correct (the 2D I mean)? I'd expect them to be vectors rather than matrices. Or do your arrays actually matrices contain row or column vectors?

Also note I used Y rather than y, to prevent confusion, since there's another y!

Also, apart from code problems, I don't immediately recognize gradient descent in your code, but that may be my limited knowledge.

def gradient_descent_lr(X,Y,alpha,iters):
    x_coef = 0
    y_int = 0
    coef_list = []

    for 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 by the error
        x_coef = x_coef - (alpha*error*x)
        coef_list.append((float(y_int),float(x_coef)))

    return coef_list

Upvotes: 1

Related Questions