只有大多数特定预测的 Keras 准确性
Keras accuracy of only most certain predictions
我正在使用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 预测的准确度。
试试这个代码:
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())
我设法使用这段代码解决了我的问题:
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 指标
我正在使用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 预测的准确度。
试试这个代码:
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())
我设法使用这段代码解决了我的问题:
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 指标