当我想计算灵敏度和特异性时,Keras中的错误

时间:2019-04-11 19:48:36

标签: keras conv-neural-network metrics

我正在编写一个代码,用于基于CNN在两种类型的图像之间进行分类。 我想测量我的工作的准确性,敏感性和特异性,但不幸的是,我遇到以下错误。 您能否让我知道我的问题是什么。

m = tf.keras.metrics.SensitivityAtSpecificity(0.5)
model.compile(optimizer='adam', loss=keras.losses.binary_crossentropy, metrics=['accuracy',m])

错误:

Traceback (most recent call last):
  File "C:/Users/Hamed/PycharmProjects/Deep Learning/CNN.py", line 77, in <module>
    validation_steps = 1600//batch_size)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\engine\training.py", line 1418, in fit_generator
    initial_epoch=initial_epoch)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\engine\training_generator.py", line 217, in fit_generator
    class_weight=class_weight)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\engine\training.py", line 1217, in train_on_batch
    outputs = self.train_function(ins)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\backend\tensorflow_backend.py", line 2715, in __call__
    return self._call(inputs)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\keras\backend\tensorflow_backend.py", line 2675, in _call
    fetched = self._callable_fn(*array_vals)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
    run_metadata_ptr)
  File "C:\Users\Hamed\Anaconda3\envs\tensorflowGPU\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.NotFoundError: Resource localhost/false_negatives/class tensorflow::Var does not exist.
     [[{{node metrics/sensitivity_at_specificity/AssignAddVariableOp_1}}]]
     [[{{node metrics/sensitivity_at_specificity/Mean}}]]

2 个答案:

答案 0 :(得分:0)

度量标准tf.keras.metrics.SensitivityAtSpecificity计算给定特异性Click here下的灵敏度。

不幸的是,Keras尚未包括敏感性和特异性指标,因此您必须按照here的规定编写自己的自定义指标。

以下是一种计算this answer处特异性的简单方法。

def specificity(y_true, y_pred):
    """
    param:
    y_pred - Predicted labels
    y_true - True labels 
    Returns:
    Specificity score
    """
    neg_y_true = 1 - y_true
    neg_y_pred = 1 - y_pred
    fp = K.sum(neg_y_true * y_pred)
    tn = K.sum(neg_y_true * neg_y_pred)
    specificity = tn / (tn + fp + K.epsilon())
    return specificity

您可以在this link上获得Keras实现的特异性和敏感性。

答案 1 :(得分:0)

如果有帮助,您可以尝试一下...

import keras

model.compile(optimizer="adam",
              loss="categorical_crossentropy",
              metrics=[keras.metrics.Precision(), keras.metrics.Recall(), keras.metrics.SpecificityAtSensitivity(0.5), keras.metrics.SensitivityAtSpecificity(0.5), 'accuracy'])