0

我无法弄清楚为什么以下程序中的 while 循环总是在 1 次迭代后停止。基本上,无论输入如何,一次迭代后 weightsPrevious 如何变得等于权重。基本上我想跟踪两次连续运行的权重列表,如果它们相等,我想退出。如果我使用具有固定大量迭代的 for 循环,我会看到连续权重列表在第一次迭代中不相等,但 while 循环总是在一次之后退出。任何帮助将不胜感激。

import random

def test(inputs, targets):
    inputDim = len(inputs[0])
    outputDim = len(targets[0])
    if (len(inputs) == len(targets)):
        dataSize = len(inputs)
    else:
        return

    weights = [];

    for i in range(inputDim + 1):
        weights.append([]);
        for j in range(outputDim):
            weights[i].append(2*random.random() - 1);

    weightsPrevious = 0

    iterCount = 0
    while (weightsPrevious != weights):
        iterCount += 1
        print("iteration", iterCount)
        weightsPrevious = weights.copy()
        for k in range(dataSize):
            for j in range(outputDim):
                weights[0][j] += 0.25*(targets[k][j] - 1)*(-1)
                for i in range(inputDim):
                    weights[i + 1][j] += 0.25*(targets[k][j] - 1)*inputs[k][i]

        return weights

test([[0,0],[0,1],[1,0],[1,1]],[[0],[1],[1],[1]])

编辑:即使删除最后一个 return 语句,我也会得到相同的结果

4

2 回答 2

4

发生这种情况是因为您return在 while 循环的末尾有一个。return停止函数的执行并返回weights

我认为您需要取消缩进:

while (weightsPrevious != weights):
    iterCount += 1
    print("iteration", iterCount)
    ...

return weights # now this is going to be executed when 
               # the while loop is finished.
于 2013-07-12T16:13:39.193 回答
0
while (weightsPrevious != weights):
    iterCount += 1
    print("iteration", iterCount)
    weightsPrevious = weights.copy()
    for k in range(dataSize):
        for j in range(outputDim):
            weights[0][j] += 0.25*(targets[k][j] - 1)*(-1)
            for i in range(inputDim):
                weights[i + 1][j] += 0.25*(targets[k][j] - 1)*inputs[k][i]

    return weights

应该

while (weightsPrevious != weights):
    iterCount += 1
    print("iteration", iterCount)
    weightsPrevious = weights.copy()
    for k in range(dataSize):
        for j in range(outputDim):
            weights[0][j] += 0.25*(targets[k][j] - 1)*(-1)
            for i in range(inputDim):
                weights[i + 1][j] += 0.25*(targets[k][j] - 1)*inputs[k][i]

return weights

注意退货上的缩进

于 2013-07-12T16:13:10.067 回答