Есть ли способ вложить итератор в цикл for - PullRequest
0 голосов
/ 05 июня 2019

так что у меня есть итератор с некоторыми опциями, я хочу вложить его в простой цикл while или for, но кажется, что это не разрешено, вот мой код.Спасибо за любую помощь заранее.

def gradientDescent(X, y, theta, alpha, num_iters):
    m = len(y)
    J_History = np.zeros(num_iters)
    theta_history = np.array([0, 0] * num_iters).reshape(2, num_iters)
    J_History[0] = computeCost(X, y, theta)

while 0 < num_iters:                                    <-- I need a outer loop for the iterator to be repeated "x" times
    with np.nditer(X, order='C', flags=['external_loop'], op_flags=['readwrite']) as it:
        for x in it:
            theta[0] = theta[0] - (alpha * (x[0] * theta[0] + x[1] * theta[1] - x[2]))/m
            theta[1] = theta[1] - ((alpha * (x[0] * theta[0] + x[1] * theta[1] - x[2]))*x[1])/m

J_History[iter] = computeCost(X, y, theta)

1 Ответ

2 голосов
/ 05 июня 2019

Как есть, num_iters не изменяется в цикле while.

Вы можете использовать цикл for:

for _ in range(num_iters):
    with np.nditer(X, order='C', flags=['external_loop'], op_flags=['readwrite']) as it:
        for x in it:
            theta[0] = theta[0] - (alpha * (x[0] * theta[0] + x[1] * theta[1] - x[2]))/m
            theta[1] = theta[1] - ((alpha * (x[0] * theta[0] + x[1] * theta[1] - x[2]))*x[1])/m

Вместо этого вы можете использовать цикл while, но вам потребуется увеличить счетчик самостоятельно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...