带有特定examp的Python变量范围

2024-09-19 23:33:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题以前有人问过,但不太适合我的情况

right = 0 
mistake = 0
plt.figure(figsize=(16,16))
for i in range(test_image_batch.shape[0]): 
    plt.subplot(12,12, i+1)
    plt.imshow(test_image_batch[i])
    plt.axis('off')
    bestnum   = 0.0
    bestclass = 0

    for j in range(10):
        if bestnum < batch_prediction_array[i][j]:
            bestnum = batch_prediction_array[i][j]
            bestclass = j
    print("bestclass", bestclass) #only gives the correct maxmimum value when bestclass is declared inside the outer for loop
    if test_label[i] == bestclass:
        plt.title(cifar10_labels[bestclass])
        right += 1
    else:
        plt.title(cifar10_labels[bestclass] + "!=" + cifar10_labels[test_label[i][0]], color='#ff0000')
        mistake += 1 

这是我的代码的一部分,搜索最大预测值并将其绘制在图表上

在我的理解中,bestclass应该有更内部作用域的值,所以当bestclass第一次在for i in range(test_image_batch.shape[0]):内部和外部声明时,bestclass应该有相同的值。bestclass仅在outer for循环内声明时为所有批处理数组[i]提供正确的最大值。当在外部for循环外声明bestclass时,它只打印第一批\u预测\u数组[i]的正确最大值

我百分之百肯定,除了上面显示的代码之外,bestclass不会在代码中的任何其他地方声明

更奇怪的是,我无法重现同样的行为

所以我的问题是我错过了什么?我明白法律的规定,但在这种特殊情况下。这似乎不符合法律规定

如果这有帮助的话,我是java背景的

EDIT:我刚刚发现,当bestclass在outer for循环外声明时,if语句被跳过,但bestclass值被更改为1(即batch_prediction_array[0][3]


Tags: intestimage声明forifbatchrange