我正在使用Keras
(基于Tensorflow
后端)进行二元分类,目前的精确率约为76%,召回率约为70%。现在我想尝试调整决策阈值。据我所知,Keras
默认使用0.5作为决策阈值。请问在Keras
中是否有办法使用自定义阈值来调整决策精确率和召回率?
谢谢你的时间!
回答:
可以这样创建自定义指标:
感谢@Marcin的编辑:创建返回所需指标的函数,并将threshold_value
作为参数
def precision_threshold(threshold=0.5): def precision(y_true, y_pred): """精确率指标。 使用threshold_value计算整个批次的精确率。 """ threshold_value = threshold # 调整之前用于获取预测的"round()"函数。裁剪以确保预测的原始值在0到1之间。 y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value), K.floatx()) # 计算真正例的数量。进行四舍五入以确保得到整数。 true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1))) # 计算预测为正的数量 predicted_positives = K.sum(y_pred) # 获取精确率比率 precision_ratio = true_positives / (predicted_positives + K.epsilon()) return precision_ratio return precisiondef recall_threshold(threshold = 0.5): def recall(y_true, y_pred): """召回率指标。 使用threshold_value计算整个批次的召回率。 """ threshold_value = threshold # 调整之前用于获取预测的"round()"函数。裁剪以确保预测的原始值在0到1之间。 y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value), K.floatx()) # 计算真正例的数量。进行四舍五入以确保得到整数。 true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1))) # 计算正目标的数量。 possible_positives = K.sum(K.clip(y_true, 0, 1)) recall_ratio = true_positives / (possible_positives + K.epsilon()) return recall_ratio return recall
现在你可以在以下代码中使用它们:
model.compile(..., metrics = [precision_threshold(0.1), precision_threshold(0.2),precision_threshold(0.8), recall_threshold(0.2,...)])
希望这对你有帮助 🙂