Home > Back-end >  TypeError: 'bool' object is not subscriptable
TypeError: 'bool' object is not subscriptable

Time:12-27

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()

CodePudding user response:

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. I.e. 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

CodePudding user response:

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]

CodePudding user response:

Your correct variable in line 3 is a boolean.

A boolean is not subscriptable, i.e., 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).

  • Related