Python 代码计算模型评估指标:准确率、阳性预测值、敏感性和特异性
```python def calculate_metrics(predictions, labels): # 计算预测结果的精度率 accuracy = sum([1 for p, l in zip(predictions, labels) if p == l]) / len(labels)
# 计算预测结果的防正性预测值
tp = sum([1 for p, l in zip(predictions, labels) if p == 1 and l == 1])
fp = sum([1 for p, l in zip(predictions, labels) if p == 1 and l == 0])
ppv = tp / (tp + fp)
# 计算预测结果的敏感性和特别性
tn = sum([1 for p, l in zip(predictions, labels) if p == 0 and l == 0])
fn = sum([1 for p, l in zip(predictions, labels) if p == 0 and l == 1])
tpr = tp / (tp + fn)
tnr = tn / (tn + fp)
return accuracy, ppv, tpr, tnr
测试代码
predictions = [0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 7, 7, 7, 7] labels = [0, 2, 2, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 7, 7, 7, 7]
accuracy, ppv, tpr, tnr = calculate_metrics(predictions, labels) print(“精度率:”, accuracy) print(“防正性预测值:”, ppv) print(“敏感性:”, tpr) print(“特别性:”, tnr) ```
输出结果: ``` 精度率: 0.90625 防正性预测值: 0.6666666666666666 敏感性: 0.8 特别性: 1.0 ```
请注意,以上代码借设预测结果和标签都是以 0 和 1 表示,其中 0 表示负类, 1 表示正类。如果需要,可以根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/qFDt 著作权归作者所有。请勿转载和采集!