【问题标题】:How to create an AUC custom function in Keras?如何在 Keras 中创建 AUC 自定义函数?
【发布时间】:2021-08-31 16:38:35
【问题描述】:

我正在尝试在 Keras 中创建两个自定义函数 f1_metric 和 auc_metric。 f1_metric 有效,但 auc 无效,我收到不同的错误。这是我的代码:

def f1_metric(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    recall = true_positives / (possible_positives + K.epsilon())
    f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())
    
    return f1_val  

def auc_metric(y_true, yhat):
    
    yhat = yhat[:, 1]

    # calculate roc curves
    fpr, tpr, thresholds = roc_curve(y_true, yhat)
    auc=auc(tpr,fpr)
    return auc

这是我的编译和拟合代码:

   opt = SGD(lr=0.01,momentum=0.9) 
   model.compile(loss='binary_crossentropy', optimizer=opt,metrics=['accuracy']) # 
   ca = SnapshotEnsemble(n_epochs, n_cycles, 0.01)

  # fit model
  history=model.fit(trainX, trainy, validation_data=(testX, testy), epochs=n_epochs, 
   verbose='auto', callbacks=[ca],batch_size=32)

任何想法如何解决它?我想定义一个与 f1_metric 类似的函数。

【问题讨论】:

标签: python tensorflow keras neural-network


【解决方案1】:

来自 cmets

近似于 ROC 或 PR 曲线的 AUC(曲线下面积)。

tf.keras.metrics.AUC(
    num_thresholds=200, curve='ROC',
    summation_method='interpolation', name=None, dtype=None,
    thresholds=None, multi_label=False, num_labels=None, label_weights=None,
    from_logits=False
)

更多详情可以参考here

(转述自特洛伊船长)

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 2020-05-29
    • 2017-10-10
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 2021-02-22
    • 2019-01-18
    相关资源
    最近更新 更多