首页 > 解决方案 > 如何根据 Keras 中的输出概率将其区分为 True 或 False?

问题描述

当我预测泰坦尼克号乘客幸存与否时,模型输出是一个概率。我怎样才能将它区分为 0 或 1?

这是模型构建

inputs = keras.layers.Input(shape=(8,))
dropout = keras.layers.Dropout(0.2)(inputs)
hidden1 = keras.layers.Dense(40, activation=tf.nn.relu)(dropout)

hidden2 = keras.layers.Dense(30, activation=tf.nn.relu)(hidden1)

hidden3 = keras.layers.Dense(20, activation=tf.nn.relu)(hidden2)

out = keras.layers.Dense(1, activation=tf.nn.sigmoid)(hidden3)
mdl = keras.models.Model(inputs=inputs, outputs=out)

当我使用经过训练的模型预测结果时,我得到的概率不是标签(0 或 1)

res = model.predict(test_data)

问题:

如何将概率映射到标签(0 或 1)?

标签: python-3.xmachine-learningkerasdeep-learningtensorflow2.0

解决方案


以下是将概率映射到离散类标签的两种方法:

方法 1:当不需要阈值时

predicted_class = round(res)     # rounds the probability value to 0 or 1

方法二:当需要设置分类阈值时

predicted_class = 1 if res>0.5 else 0     # here threshold = 0.5 and can be fine-tuned based on the observed precision and recall scores

推荐阅读