Keras自定义决策阈值以提高精确率和召回率

我正在使用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,...)])

希望这对你有帮助 🙂

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注