【问题标题】:Keras accuracy of only most certain predictionsKeras 仅对大多数特定预测的准确性
【发布时间】:2021-02-08 17:41:47
【问题描述】:

我正在使用 keras 执行二进制分类(单标签,一或零)。

我想创建一个自定义指标,从预测中提取最高 10% 并计算其准确性。

例如使用标签 [1, 0, 1, 1, 0, 1, 0, 1, 0, 1]

和预测 [0.5, 0.7, 0.98, 0.1, 0.2, 0.5, 0.2, 0.1, 0.9, 0.8]

它只计算 0.98 预测的准确度。

【问题讨论】:

    标签: python-3.x tensorflow machine-learning keras artificial-intelligence


    【解决方案1】:

    试试这个代码:

    import tensorflow as tf
    
    def accuracy_metric_fn(y_true, y_pred):
      l = len(y_pred) // 10
      top = tf.math.top_k(y_pred, l)
      y_pred = top.values
      y_true = tf.gather(y_true, top.indices)
      y_true = tf.cast(y_true, tf.float32)
      loss = tf.keras.metrics.binary_accuracy(
          y_true, y_pred)
      return loss
    
    y_true = [1, 0, 1, 1, 0, 1, 0, 1, 0, 1]
    y_pred = [0.5, 0.7, 0.98, 0.1, 0.2, 0.5, 0.2, 0.1, 0.9, 0.8]
    print(accuracy_metric_fn(y_true, y_pred).numpy())
    

    【讨论】:

    • 使用该指标进行训练时仍然出现错误:
    • InvalidArgumentError: 输入必须至少有 k 列。有 1 个,需要 4 个 [[node TopKV2 (defined at :7) ]] [Op:__inference_train_function_33430] 错误可能源于输入操作。连接到节点 TopKV2 的输入源操作:functional_5/dense_5/Sigmoid(定义在 :2) floordiv(定义在 :6) 函数调用堆栈:train_function
    【解决方案2】:

    我设法使用此代码解决了我的问题:

    import tensorflow as tf
    
    def topacc(y_true, y_pred):
      k = tf.cast(len(y_true) // 10, 'int64')
      y_true, y_pred = tf.transpose(y_true), tf.transpose(y_pred)
      return tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=k)
    

    这是一个完整的 keras 指标

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 2021-06-06
      • 2016-06-03
      • 2017-12-13
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2015-06-18
      • 2019-04-23
      相关资源
      最近更新 更多