多分类任务中特异度计算代码
时间: 2024-11-25 12:15:50 浏览: 44
在多分类任务中,特异性(Specificity)通常用于评估模型预测的准确性,特别是当我们关注的是避免将负样本误判为正样本的能力时。特异性计算公式是:
\[ Specificity = \frac{True Negative}{True Negative + False Positive}\]
其中:
- True Negative (真阴性) 表示实际为负类(比如非疾病、非异常等)而被模型预测为负类的情况。
- False Positive (假阳性) 表示实际为负类却被模型错误预测为正类。
以下是一个简单的Python代码示例,假设我们有预测结果(y_pred)和真实标签(y_true),可以计算每个类别的特异性:
```python
import numpy as np
# 假设y_pred是模型预测的概率数组,y_true是对应的真实标签(0表示负类,1表示正类)
y_pred = np.array([...]) # 预测概率
y_true = np.array([...]) # 真实标签
# 将标签转换为二进制形式(0 或 1)
y_pred_binary = np.argmax(y_pred, axis=1)
y_true_binary = y_true.astype(int)
# 计算特异性
specificities = []
for class_idx in range(np.unique(y_true).shape[0]):
true_negatives = np.sum((y_true_binary == class_idx) & (y_pred_binary != class_idx))
false_positives = np.sum((y_true_binary != class_idx) & (y_pred_binary == class_idx))
if false_positives > 0: # 防止除数为零
specificity = true_negatives / (true_negatives + false_positives)
specificities.append(specificity)
else:
specificities.append(0) # 如果不存在假阳性的例子,特异性为0
# 整理成字典或数据结构,便于查看各类别特异性
specificity_dict = {f"class_{i}": specificity for i, specificity in enumerate(specificities)}
阅读全文
相关推荐















