python-3.x - 如何根据 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)?
解决方案
以下是将概率映射到离散类标签的两种方法:
方法 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
推荐阅读
- react-native - React Native 和 React Navigation - 如何让屏幕标题显示在标题和底部选项卡导航器中也显示
- hibernate - 为单个瞬态对象创建重复条目
- javascript - 如何在新文档 onCreate 中添加字段?
- azure-devops - 有没有办法在 Azure DevOps CI/CD 构建管道中设置日期和时间(时区)
- angular - 如何修复“无法解构未定义或空的属性扩展”
- rest - 如何在使用 JWT 的 asp.net 核心 Web 应用和 Web api 中使用 google authenticaion
- reactjs - 如何在 Reactjs 中使用 mobx 渲染之前更新状态
- json - 在 ionic 中以 JSON 格式保存数组
- ios - 可绑定属性未更新 iOS 上的视图
- rust - 错误[E0599]:在当前范围内没有为类型“&mut G”找到名为“gen”的方法