Skip to content

Instantly share code, notes, and snippets.

@iwanbolzern
Created October 9, 2019 06:35
Show Gist options
  • Save iwanbolzern/142e5008095c2efff0a429d08b85e661 to your computer and use it in GitHub Desktop.
Save iwanbolzern/142e5008095c2efff0a429d08b85e661 to your computer and use it in GitHub Desktop.
function to convert an sklearn confusion_matrix into a string representation
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