遍历浮点概率列表与阈值列表比较生成预测结果的问题
问题与解决方案
问题需求
需要遍历浮点概率列表,将每个概率与阈值列表中的每个阈值做大于等于比较,生成对应5个阈值的5个预测列表。运行代码时出现float is not iterable、cannot compare between int and float type、truth is ambiguous等错误,尝试多种方法仍未解决。
错误代码如下:
probs = [0.886,0.375,0.174,0.817,0.574,0.319,0.812,0.314,0.098,0.741, 0.847,0.202,0.31,0.073,0.179,0.917,0.64,0.388,0.116,0.72] thresholds = [0.00, 0.25, 0.50, 0.75, 1.00] x={} for i in thresholds: if i <= probs #comparing one value of thresholds to all values of probs x.append(0) else: x.append(1)
错误原因分析
- 容器类型误用:把字典
x当成列表调用append()方法,字典没有该方法,需用列表或字典存储每个阈值对应的结果集 - 比较逻辑错误:直接用单个阈值
i和整个probs列表比较,Python无法判断单个数值与列表的大小关系,触发truth is ambiguous错误 - 遍历逻辑缺失:未遍历
probs中的每个元素,无法完成单个概率与阈值的逐一比较
正确实现代码
方法1:用字典存储每个阈值对应的预测列表
probs = [0.886,0.375,0.174,0.817,0.574,0.319,0.812,0.314,0.098,0.741, 0.847,0.202,0.31,0.073,0.179,0.917,0.64,0.388,0.116,0.72] thresholds = [0.00, 0.25, 0.50, 0.75, 1.00] # 用字典存储每个阈值对应的预测结果 predictions = {} for threshold in thresholds: # 遍历每个概率,和当前阈值比较生成预测列表 pred_list = [1 if prob >= threshold else 0 for prob in probs] predictions[threshold] = pred_list # 打印结果示例 for thresh, preds in predictions.items(): print(f"阈值{thresh}对应的预测列表: {preds}")
方法2:用列表存储所有预测列表(按阈值顺序)
probs = [0.886,0.375,0.174,0.817,0.574,0.319,0.812,0.314,0.098,0.741, 0.847,0.202,0.31,0.073,0.179,0.917,0.64,0.388,0.116,0.72] thresholds = [0.00, 0.25, 0.50, 0.75, 1.00] predictions_list = [] for threshold in thresholds: pred_list = [1 if prob >= threshold else 0 for prob in probs] predictions_list.append(pred_list) # 打印结果示例 for idx, preds in enumerate(predictions_list): print(f"第{idx+1}个阈值({thresholds[idx]})对应的预测列表: {preds}")
说明
- 用列表推导式遍历每个概率与阈值比较,逻辑清晰且高效
- 预测逻辑为:概率≥阈值时标记为1,否则为0,可根据需求调换
1和0的位置 - 彻底解决了类型不匹配、不可迭代、真值模糊的问题
内容的提问来源于stack exchange,提问作者Chase Stahl
相关产品推荐
相关产品推荐

