简体   繁体   中英

TypeError: 'bool' object is not subscriptable

I get the following error:

TypeError: 'bool' object is not subscriptable

for the following code. I'm new to Python and I don't know how to solve it. Hoping it's a simple fix but don't know enough


def get_correct_indices(model, x, labels):
    y_model = model(x)
    correct = np.argmax(y_model.mean(), axis=1) == np.squeeze(labels)
    correct_indices = [i for i in range(x.shape[0]) if correct[i]]
    incorrect_indices = [i for i in range(x.shape[0]) if not correct[i]]
    return correct_indices, incorrect_indices


def plot_entropy_distribution(model, x, labels):
    probs = model(x).mean().numpy()
    entropy = -np.sum(probs * np.log2(probs), axis=1)
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    for i, category in zip(range(2), ['Correct', 'Incorrect']):
        entropy_category = entropy[get_correct_indices(model, x, labels)[i]]
        mean_entropy = np.mean(entropy_category)
        num_samples = entropy_category.shape[0]
        title = category + 'ly labelled ({:.1f}% of total)'.format(num_samples / x.shape[0] * 100)
        axes[i].hist(entropy_category, weights=(1/num_samples)*np.ones(num_samples))
        axes[i].annotate('Mean: {:.3f} bits'.format(mean_entropy), (0.4, 0.9), ha='center')
        axes[i].set_xlabel('Entropy (bits)')
        axes[i].set_ylim([0, 1])
        axes[i].set_ylabel('Probability')


        axes[i].set_title(title)
    plt.show()

Your correct variable in line 3 is a boolean.

A boolean is not subscriptable, ie, it is not a storage class, such as Python's list object. Thus, you cannot use [] to index it (as it is not storing an array of values).

It is not easy to execute your code and test it. However I think you should try to run it, and print all substripted objects in order to debug your code. Ie print ´correct' in your first function And get_correct_indices in your second function See what happens… Otherwise, try sending a code which can be executed for testing

The problem is that you can not use [] operator with boolean. The problem seems to be in this two lines:

    correct = np.argmax(y_model.mean(), axis=1) == np.squeeze(labels)
    correct_indices = [i for i in range(x.shape[0]) if correct[i]]

See, correct is a boolean variable and you try to access it with correct[i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM