使用Keras构建自定义损失函数指标,错误为

时间:2017-06-17 20:14:32

标签: customization keras conv-neural-network metrics loss-function

我正在尝试编写自定义度量函数,以便以这种方式编写的编译步骤中设置:

self.model.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=[self.dice_similarity_coefficient_metric,self.positive_predictive_value_metric,self.sensitivity_metric])

我用这种方式写了骰子相似系数,正预测值和相似度:

  • FP =误报
  • TP = true positive
  • FN =假阴性
 def dice_similarity_coefficient_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) & 
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array((2 * TP) / (FP + (2 * TP) + FN + 
        K.epsilon())))
    def positive_predictive_value_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        return K.variable(np.array(TP / (FP + TP + K.epsilon())))
    def sensitivity_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) & 
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array(TP / (TP + FN + K.epsilon())))

当我运行代码时,我有以下错误:

  

InvalidArgumentError(请参阅上面的回溯):您必须使用dtype float为占位符张量'dense_3_target'提供值        [[节点:dense_3_target = Placeholderdtype = DT_FLOAT,shape = [],_ device =“/ job:localhost / replica:0 / task:0 / cpu:0”]]

有人可以解释问题的位置吗? 哪里我错了?

谢谢

1 个答案:

答案 0 :(得分:0)

使用后端功能定义指标可能更好。例如:

def false_negatives(Y_true, Y_pred):
    return K.sum(K.round(K.clip(Y_true - Y_pred, 0, 1)))

可以使用5 FN检查示例数据:

y_true = np.array([[1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], dtype=np.float32)
y_pred = np.array([[0.3, 0.99, 0.99, 0.1], [0.6, 0.99, 0.99, 0.1], [0.1, 0.99, 0.99, 0.1]], dtype=np.float32)
n_fn = np.sum((y_true - y_pred) > 0.5)
Y_true = K.placeholder((None, 4), dtype=K.floatx())
Y_pred = K.placeholder((None, 4), dtype=K.floatx())
n_fn = false_negatives(Y_true, Y_pred).eval(inputs_to_values={Y_true: y_true, Y_pred: y_pred})

HTH