在R语言中计算表格的对角线比例(总体准确率)
Hey there! Let's walk through how to compute the overall accuracy (the proportion of diagonal elements in your table) step by step.
First, let's align on the concept: overall accuracy here is the ratio of correctly classified samples (values where the row label matches the column label—these are the diagonal elements) to the total number of samples in the table.
Step 1: Fix the Table Data (if needed)
Your dput output was truncated, so let's reconstruct the correct table using the details from your str(a) and printed table:
# Recreate your table object a <- structure( c(421L, 100L, 409L, 113L, 31L, 17L, 10L, 12L, 1L, 2L, 3L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), .Dim = c(2L, 10L), .Dimnames = structure( list( scores = c("0", "1"), c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9") ), .Names = c("scores", "") ) )
Step 2: Compute the Accuracy
You can calculate the overall accuracy with just a few simple lines of R code:
# Sum the diagonal elements (these are the correct predictions) correct_predictions <- sum(diag(a)) # Sum all elements in the table (total number of samples) total_samples <- sum(a) # Calculate the accuracy ratio overall_accuracy <- correct_predictions / total_samples # Print the result in a readable format cat("Overall Accuracy:", round(overall_accuracy, 4), "or", round(overall_accuracy * 100, 2), "%\n")
Breakdown of the Code
diag(a)pulls out the diagonal values from your table: for your data, that's421(row "0" matches column "0") and113(row "1" matches column "1").sum(diag(a))adds these correct predictions together:421 + 113 = 534.sum(a)calculates the total number of samples in the table: in your case, that's1120.- Dividing these gives the accuracy:
534 / 1120 ≈ 0.4768(or ~47.68%).
Quick Note
This method works for any size of confusion matrix—whether your table has 2 rows or 20, the diagonal always represents matches between row and column labels, so the logic stays the same.
内容的提问来源于stack exchange,提问作者Avi

