用python编写分类性能度量的函数 my_metrics(y,y_predict), 要求(不使用 sklearn)返 回准确度、精确率、召回率和 F1 score。
时间: 2024-10-29 22:13:06 浏览: 18
Python库 | jmeter_metrics-1.0.4-py3-none-any.whl
当然可以。在Python中,我们可以手动计算这些常见的分类性能指标,不需要依赖sklearn库。这里是一个简单的示例函数`my_metrics`,它接受真实标签`y`和预测标签`y_predict`作为输入:
```python
def my_metrics(y, y_predict):
# 确保预测和实际标签都是整数数组
assert isinstance(y, np.ndarray) and isinstance(y_predict, np.ndarray)
assert y.shape == y_predict.shape
# 计算准确度
accuracy = np.sum(y == y_predict) / len(y)
# 计算混淆矩阵
tp = np.sum((y == 1) & (y_predict == 1))
tn = np.sum((y == 0) & (y_predict == 0))
fp = np.sum((y == 0) & (y_predict == 1))
fn = np.sum((y == 1) & (y_predict == 0))
# 精确率(Precision)
precision = tp / (tp + fp) if tp + fp != 0 else 0
# 召回率(Recall)
recall = tp / (tp + fn) if tp + fn != 0 else 0
# F1 Score
f1_score = 2 * precision * recall / (precision + recall) if precision + recall != 0 else 0
return accuracy, precision, recall, f1_score
# 示例用法
y = [0, 1, 1, 0, 1]
y_predict = [0, 1, 1, 0, 1]
acc, prec, rec, f1 = my_metrics(y, y_predict)
print(f"Accuracy: {acc}, Precision: {prec}, Recall: {rec}, F1 Score: {f1}")
阅读全文