TypeError:' bool'对象没有属性' __ getitem __'

时间:2017-04-05 15:06:01

标签: python-2.7 keras conv-neural-network

我使用keras训练了一个cnn,

%%time
scores = model.evaluate(x_test, y_test, verbose=2)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

我得到了以下结果

acc: 67.62%
CPU times: user 1.66 s, sys: 836 ms, total: 2.49 s
Wall time: 447 ms

我想使用函数show_failures()来更详细地检查故障。例如,以下是真正的类是" 6"。

的失败

使用

进行预测后
predictions = model.predict(x_test)

l定义:

def show_failures(predictions, trueclass=None, predictedclass=None, maxtoshow=10):
    rounded = np.argmax(predictions, axis=1)
    errors = rounded!=y_test
    print('Showing max', maxtoshow, 'first failures. '
          'The predicted class is shown first and the correct class in parenthesis.')
    ii = 0
    plt.figure(figsize=(maxtoshow, 1))
    for i in range(X_test.shape[0]):
        if ii>=maxtoshow:
            break
        if errors[i]:
            if trueclass is not None and y_test[i] != trueclass:
                continue
            if predictedclass is not None and predictions[i] != predictedclass:
                continue
            plt.subplot(1, maxtoshow, ii+1)
            plt.axis('off')
            if K.image_dim_ordering() == 'th':
                plt.imshow(X_test[i,0,:,:], cmap="gray")
            else:
                plt.imshow(X_test[i,:,:,0], cmap="gray")
            plt.title("%d (%d)" % (rounded[i], y_test[i]))
            ii = ii + 1

我收到了以下错误:

Showing max 10 first failures. The predicted class is shown first and the correct class in parenthesis.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-67c05a85372a> in <module>()
      1 predictions = model.predict(x_test)
      2 
----> 3 show_failures(predictions)

<ipython-input-77-878906bfc03b> in show_failures(predictions, trueclass, predictedclass, maxtoshow)
      9         if ii>=maxtoshow:
     10             break
---> 11         if errors[i]:
     12             if trueclass is not None and y_test[i] != trueclass:
     13                 continue

TypeError: 'bool' object has no attribute '__getitem__'

<matplotlib.figure.Figure at 0x7f9b8af32150>

1 个答案:

答案 0 :(得分:1)

您需要对round和y_test执行 EXCLUSIVE OR 来构建错误。最简单的方法(没有任何库)是:

errors = [x!=y for x, y in zip(rounded, y_test)]