2017-04-06 37 views
6

我试图实现keras的AUC度量,以便在model.fit()运行期间运行验证集后运行AUC度量。定义keras的AUC度量标准以支持验证数据集的评估

我定义的指标,因为这:

def auc(y_true, y_pred): 
    keras.backend.get_session().run(tf.global_variables_initializer()) 
    keras.backend.get_session().run(tf.initialize_all_variables()) 
    keras.backend.get_session().run(tf.initialize_local_variables()) 

    #return K.variable(value=tf.contrib.metrics.streaming_auc(
    # y_pred, y_true)[0], dtype='float32') 
    return tf.contrib.metrics.streaming_auc(y_pred, y_true)[0] 

这将导致以下错误,我不知道理解。

tensorflow.python.framework.errors_impl.FailedPreconditionError: 
Attempting to use uninitialized value auc/true_positives... 

从网上阅读,似乎问题是2倍,在tensorflow/keras中的错误和部分和问题与tensorflow暂时无法从推理初始化局部变量。鉴于这两个问题,我不明白为什么我会得到这个错误或如何克服它。有什么建议么?

为了证明我不是懒惰的,我写了2个其他指标可以正常工作。

# PFA, prob false alert for binary classifier 
def binary_PFA(y_true, y_pred, threshold=K.variable(value=0.5)): 
    y_pred = K.cast(y_pred >= threshold, 'float32') 
    # N = total number of negative labels 
    N = K.sum(1 - y_true) 
    # FP = total number of false alerts, alerts from the negative class labels 
    FP = K.sum(y_pred - y_pred * y_true)  
    return FP/N 

# P_TA prob true alerts for binary classifier 
def binary_PTA(y_true, y_pred, threshold=K.variable(value=0.5)): 
    y_pred = K.cast(y_pred >= threshold, 'float32') 
    # P = total number of positive labels 
    P = K.sum(y_true) 
    # TP = total number of correct alerts, alerts from the positive class labels 
    TP = K.sum(y_pred * y_true)  
    return TP/P 

回答

0

你需要运行tf.initialize_local_variables()返回的AUC张

def auc(y_true, y_pred): 
    auc = tf.metrics.auc(y_true, y_pred)[1] 
    K.get_session().run(tf.local_variables_initializer()) 
    return auc 

这将初始化TP,FP,TN,FN为零之前。请注意,由于TP,FP,TN,FN变量必须在每次运行后初始化为零,因此这只会在第一次计算出正确的auc得分时才提供。