从给定范围内的张量中删除值

Remove values from a tensor that are within a given range

我希望能够知道当预测高于或低于某个阈值时我的神经网络的舍入精度。例如,我希望它仅在预测高于 0.55 或低于 0.45 时计算准确度,以便过滤掉接近 50/50 的情况。

我尝试在 Whosebug 上使用 soft_acc 函数并在开头添加一个 if else 以过滤掉接近 50/50 的部分。

def soft_acc(y_true, y_pred):
    if y_pred > 0.55 or y_pred < 0.45:
        return K.mean(K.equal(K.round(y_true), K.round(y_pred)))

我收到以下错误消息。

TypeError:不允许将 tf.Tensor 用作 Python bool。使用 if t is not None: 而不是 if t: 来测试是否定义了张量,并使用诸如 tf.cond 之类的 TensorFlow 操作来执行以张量值为条件的子图。

使用 tf.boolean_mask 过滤掉不符合要求阈值的索引值。

# remove values from `X` in interval (lo, hi)
mask = tf.math.logical_or(tf.lesser(X, lo), tf.greater(X, hi))
X = tf.boolean_mask(X, mask)

在您的情况下,您可以将 soft_acc 定义为

def soft_acc(y_true, y_pred):
    mask = tf.math.logical_or(tf.greater(y_pred, 0.55), tf.lesser(y_pred, 0.45))
    y_true2 = tf.boolean_mask(y_true, mask)
    y_pred2 = tf.boolean_mask(y_pred, mask)

    return K.mean(K.equal(K.round(y_true2), K.round(y_pred2)))