Python 3.x ';布尔';对象不可下标-Keras

Python 3.x ';布尔';对象不可下标-Keras,python-3.x,numpy,keras,Python 3.x,Numpy,Keras,我目前参与了一个深度学习项目,我需要使用灵敏度和特异性指标对其进行评估,这不包括在keras开箱即用中 我已经实现了如下灵敏度功能: from keras import backend as K def sensitivity(y, y_pred): TP = 0 FP = 0 TN = 0 FN = 0 for i in range(5): true = (y == i) preds = (y_pred == i)

我目前参与了一个深度学习项目,我需要使用灵敏度和特异性指标对其进行评估,这不包括在keras开箱即用中

我已经实现了如下灵敏度功能:

from keras import backend as K

def sensitivity(y, y_pred):
    TP = 0
    FP = 0
    TN = 0
    FN = 0
    for i in range(5):
        true = (y == i)
        preds = (y_pred == i)
        print(preds)
        TP += K.sum(preds[true == 1])
        FP += K.sum(true[np.invert(preds) == 1])
        TN += K.sum(np.invert(preds)[true == 1])
        FN += K.sum(true[preds == 0])
    return TP / (TP + FN)
这本身就可以很好地工作。但是,当我试图在编译模型时使用它时,会出现错误“'bool'对象不可订阅”

我怎样才能解决这个问题

下面包含编译代码和完整的错误消息。非常感谢。 编辑:通过下面的回复和一些研究,我能够修复我粘贴在文章底部的代码。在Keras中编译模型时,它由Theano或TensorFlow进行评估,因此您不能使用Numpy命令来制定自己的度量

from keras.datasets import mnist
from keras.applications.vgg16 import VGG16

(x_train, y_train), (x_test, y_test) = mnist.load_data()

model = VGG16(
    include_top=False,
    weights='imagenet',
    input_tensor=None,
    input_shape=None,
    pooling=None,
    classes=10)

model.compile(optimizer='rmsprop',
    loss='categorical_crossentropy',
    metrics=['accuracy', sensitivity])

TypeError回溯(最近一次调用)
在()
9.model.compile(optimizer='rmsprop',
10损失=分类交叉熵',
--->11个指标=[‘准确性’,敏感性])
/编译中的home/USER/Documents/deep\u learning/custom\u metrics/venv/lib/python3.6/site-packages/keras/engine/training.py(self、optimizer、loss、metrics、loss\u weights、sample\u weight\u mode、weights\u metrics、target\u tensors、**kwargs)
449输出度量=嵌套度量[i]
450输出加权度量=嵌套加权度量[i]
-->451处理度量(输出度量)
452处理度量(输出加权度量,权重=权重)
453
/home/USER/Documents/deep_learning/custom_metrics/venv/lib/python3.6/site-packages/keras/engine/training.py in handle_metrics(指标、权重)
418度量结果=加权度量fn(y_真,y_pred,
419重量=重量,
-->420掩码=掩码[i])
421
422#将self.metrics_名称、self.metric_张量,
/home/USER/Documents/deep_learning/custom_metrics/venv/lib/python3.6/site-packages/keras/engine/training_utils.py in weighted(y_true,y_pred,weights,mask)
402  """
403#分数_数组的ndim>=2
-->404分数数组=fn(y_真,y_pred)
405如果掩码不是无:
406#将遮罩投射到floatX,以避免float64向上投射
灵敏度(y,y_pred)
11 preds=(y_pred==i)
12份印刷品(preds)
--->13 TP+=K.sum(preds[true==1])
14 FP+=K.sum(真[np.invert(preds)==1])
15 TN+=K.sum(np.invert(preds)[真==1])
TypeError:“bool”对象不可下标
def灵敏度(y,y_pred):
TP=0
FP=0
TN=0
FN=0
对于范围(5)中的i:
真=K等于(y,i)
preds=K.equal(y_pred,i)
TP+=K.sum(K.cast(tf.boolean_mask(preds,tf.math.equal(true,true)),'int32'))
FP+=K.sum(K.cast(tf.boolean_mask(true,tf.math.equal(~preds,true)),'int32'))
TN+=K.sum(K.cast(tf.boolean_mask(~preds,tf.math.equal(true,true)),'int32'))
FN+=K.sum(K.cast(tf.boolean_mask(true,tf.math.equal(preds,False)),'int32'))
返回TP/(TP+FN)

这些是TensorFlow张量,而不是NumPy数组,因此您必须以不同的方式使用它们。将
true=(y==i)
替换为
true=K.equal(y,i)
preds[true==1]将是
tf.boolean_掩码(preds,tf.equal(true,1))
tf.gather(preds,tf.where(tf.equal.true,1))[:,0])
使用TensorFlow,我不确定你会如何使用纯Keras后端。
np.invert(preds)
将是
tf.bitwise.invert(preds)
使用TensorFlow或只是
~preds
。这些是TensorFlow张量,而不是NumPy数组,因此你必须以不同的方式使用它们。替换类似
true=(y==I)的东西
true=K.equal(y,i)
preds[true==1]
将是
tf.boolean_掩码(preds,tf.equal(true,1))
tf.gather(preds,tf.where(tf.equal(true,1))
使用TensorFlow,我不确定如何使用纯Keras后端。
np.invert(preds)
将是
tf.bitwise.invert(preds)
使用TensorFlow或仅使用
~preds
TypeError                                 Traceback (most recent call last)
<ipython-input-20-46c5d210c7ea> in <module>()
     9 model.compile(optimizer='rmsprop',
     10               loss='categorical_crossentropy',
---> 11               metrics=['accuracy', sensitivity])

/home/USER/Documents/deep_learning/custom_metrics/venv/lib/python3.6/site-packages/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    449  output_metrics = nested_metrics[i]
    450  output_weighted_metrics = nested_weighted_metrics[i]
--> 451  handle_metrics(output_metrics)
    452  handle_metrics(output_weighted_metrics, weights=weights)
    453 

/home/USER/Documents/deep_learning/custom_metrics/venv/lib/python3.6/site-packages/keras/engine/training.py in handle_metrics(metrics, weights)
    418  metric_result = weighted_metric_fn(y_true, y_pred,
    419  weights=weights,
--> 420  mask=masks[i])
    421 
    422  # Append to self.metrics_names, self.metric_tensors,

/home/USER/Documents/deep_learning/custom_metrics/venv/lib/python3.6/site-packages/keras/engine/training_utils.py in weighted(y_true, y_pred, weights, mask)
    402  """
    403  # score_array has ndim >= 2
--> 404  score_array = fn(y_true, y_pred)
    405  if mask is not None:
    406       # Cast the mask to floatX to avoid float64 upcasting in Theano

<ipython-input-18-caa661fb93ac> in sensitivity(y, y_pred)
     11  preds = (y_pred == i)
     12  print(preds)
---> 13  TP += K.sum(preds[true == 1])
     14  FP += K.sum(true[np.invert(preds) == 1])
     15  TN += K.sum(np.invert(preds)[true == 1])

TypeError: 'bool' object is not subscriptable

def sensitivity(y, y_pred):
    TP = 0
    FP = 0
    TN = 0
    FN = 0
    for i in range(5):
        true = K.equal(y, i)
        preds = K.equal(y_pred, i)
        TP += K.sum(K.cast(tf.boolean_mask(preds, tf.math.equal(true, True)), 'int32'))
        FP += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(~preds, True)), 'int32'))
        TN += K.sum(K.cast(tf.boolean_mask(~preds, tf.math.equal(true, True)), 'int32'))
        FN += K.sum(K.cast(tf.boolean_mask(true, tf.math.equal(preds, False)), 'int32'))
    return TP / (TP + FN)