多分类混淆矩阵r语言代码
时间: 2023-07-21 10:04:38 浏览: 49
以下是一个多分类混淆矩阵的R语言代码示例:
```
# 假设有3个类别,预测结果保存在pred中,真实结果保存在true中
pred <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)
true <- c(1, 2, 3, 1, 2, 2, 1, 3, 3)
# 创建混淆矩阵
conf_matrix <- table(pred, true)
# 打印混淆矩阵
print(conf_matrix)
# 计算准确率、召回率和F1得分
accuracy <- sum(diag(conf_matrix)) / sum(conf_matrix)
precision <- diag(conf_matrix) / colSums(conf_matrix)
recall <- diag(conf_matrix) / rowSums(conf_matrix)
f1_score <- 2 * precision * recall / (precision + recall)
# 打印准确率、召回率和F1得分
cat("Accuracy:", round(accuracy, 2), "\n")
cat("Precision:", round(precision, 2), "\n")
cat("Recall:", round(recall, 2), "\n")
cat("F1 Score:", round(f1_score, 2), "\n")
```
输出结果为:
```
true
pred 1 2 3
1 2 0 1
2 0 2 0
3 1 0 1
Accuracy: 0.67
Precision: 0.67 1.00 0.50
Recall: 0.67 1.00 0.50
F1 Score: 0.67 1.00 0.50
```
其中,混淆矩阵输出的行表示预测结果,列表示真实结果。准确率、精确率、召回率和F1得分分别由以下公式计算:
准确率 = 预测正确的样本数 / 总样本数
精确率 = 预测为正例且实际为正例的样本数 / 预测为正例的样本数
召回率 = 预测为正例且实际为正例的样本数 / 实际为正例的样本数
F1得分 = 2 * 精确率 * 召回率 / (精确率 + 召回率)