在Keras中如何根据输出概率来判别True或False?

How can I discriminate it as True or False according to the ouput probability in Keras?

当我预测泰坦尼克号乘客生还与否时,模型输出的是一个概率。我如何区分它是 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)?

这里有两种将概率映射到离散 class 标签的方法:

方法 1:不需要阈值时

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

方法二:当需要设置阈值进行class化

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