Created
October 9, 2019 06:35
-
-
Save iwanbolzern/142e5008095c2efff0a429d08b85e661 to your computer and use it in GitHub Desktop.
function to convert an sklearn confusion_matrix into a string representation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def confusion_matrix_to_str(cm, labels: List[str], precision: int = 0) -> str: | |
# get int portion of biggest number | |
max_entry = len(str(int(cm.flatten().max()))) | |
column_width = max([len(x) for x in labels]) | |
column_width = max(column_width, max_entry + 1 + precision) # + 1 is because the dot (max_entry.precision) | |
str_rep = ' ' * column_width + '\t' | |
# Print header | |
for label in labels: | |
str_rep += f'{label:{column_width}s}\t' | |
str_rep += '\n' | |
# Print rows | |
for i, label in enumerate(labels): | |
str_rep += f'{label:{column_width}s}\t' | |
for j in range(len(labels)): | |
entry = f'{cm[i, j]:.{precision}f}' | |
str_rep += entry | |
str_rep += ' ' * (column_width - len(entry)) | |
str_rep += '\t' | |
str_rep += '\n' | |
return str_rep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment