Python中如何求预测值为1且预测正确的样本个数?
有一个二分类问题,predict 为预测值,labels 为实际标签,请问一下如何显示预测值为 1 且预测正确的样本个数?
Python中如何求预测值为1且预测正确的样本个数?
5 回复
# 假设你有真实标签y_true和预测标签y_pred
import numpy as np
# 示例数据
y_true = np.array([1, 0, 1, 1, 0, 1, 0, 0, 1, 0])
y_pred = np.array([1, 0, 1, 0, 0, 1, 1, 0, 1, 0])
# 方法1:使用布尔索引直接计算
correct_predictions = (y_true == y_pred) # 所有预测正确的样本
predicted_as_1 = (y_pred == 1) # 所有预测为1的样本
# 同时满足两个条件的样本数
count = np.sum(correct_predictions & predicted_as_1)
print(f"预测为1且正确的样本数: {count}")
# 方法2:分步计算更清晰
# 找出预测为1的索引
pred_1_indices = np.where(y_pred == 1)[0]
# 在这些索引中检查是否预测正确
count = np.sum(y_true[pred_1_indices] == y_pred[pred_1_indices])
print(f"预测为1且正确的样本数: {count}")
# 方法3:使用列表推导式(适合小数据)
count = sum(1 for true, pred in zip(y_true, y_pred) if pred == 1 and true == pred)
print(f"预测为1且正确的样本数: {count}")
# 如果要获取具体的样本索引
indices = np.where((y_true == y_pred) & (y_pred == 1))[0]
print(f"符合条件的样本索引: {indices}")
核心思路:同时满足两个条件——预测值等于1,且预测值等于真实值。
建议:用布尔运算直接筛选最简洁。
result 是二维数组,[predict, label]
len(np.where(result==(1,1))[0])
np.sum(predict > 0.5 == label)
没必要非得一条命令写吧?
在预测正确里,统计预测值为 1 的数量就行了。
或者你用 sklearn 之类的库的话,可以用库函数算出 confusion matrix。
这样 TP, TN, FP, FN 都有了。
谢谢楼上三位,楼上的每个建议我都要查半天资料,长了不少知识----我是个初学者。
回 diggerdu: 用 np.sum(predict > 0.5 == label)这条语句怎么出现这个警告呀?
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

