推荐答案
在 R 语言中,可以通过以下方式计算准确率、精确率、召回率和 F1 值:
// www.javascriptcn.com code example
# 假设我们有以下混淆矩阵
conf_matrix <- matrix(c(50, 10, 5, 35), nrow = 2, byrow = TRUE)
colnames(conf_matrix) <- c("Predicted Positive", "Predicted Negative")
rownames(conf_matrix) <- c("Actual Positive", "Actual Negative")
# 计算准确率 (Accuracy)
accuracy <- sum(diag(conf_matrix)) / sum(conf_matrix)
# 计算精确率 (Precision)
precision <- conf_matrix[1, 1] / sum(conf_matrix[, 1])
# 计算召回率 (Recall)
recall <- conf_matrix[1, 1] / sum(conf_matrix[1, ])
# 计算 F1 值 (F1 Score)
f1_score <- 2 * (precision * recall) / (precision + recall)
# 输出结果
cat("Accuracy:", accuracy, "\n")
cat("Precision:", precision, "\n")
cat("Recall:", recall, "\n")
cat("F1 Score:", f1_score, "\n")本题详细解读
1. 混淆矩阵
混淆矩阵是评估分类模型性能的基础工具。它展示了模型预测结果与实际结果的对比情况。通常,混淆矩阵的形式如下:
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | True Positive (TP) | False Negative (FN) |
| Actual Negative | False Positive (FP) | True Negative (TN) |
2. 准确率 (Accuracy)
准确率是模型预测正确的样本数占总样本数的比例。计算公式为:
[ \text{Accuracy} = \frac{\text{TP} + \text{TN}}{\text{TP} + \text{TN} + \text{FP} + \text{FN}} ]
3. 精确率 (Precision)
精确率是模型预测为正类的样本中,实际为正类的比例。计算公式为:
[ \text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}} ]
4. 召回率 (Recall)
召回率是实际为正类的样本中,模型预测为正类的比例。计算公式为:
[ \text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}} ]
5. F1 值 (F1 Score)
F1 值是精确率和召回率的调和平均数,用于综合评估模型的性能。计算公式为:
[ \text{F1 Score} = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} ]
通过以上公式和代码,可以在 R 语言中轻松计算这些评估指标。