Skip to content

Instantly share code, notes, and snippets.

@vikash512
Forked from zachguo/print_cm.py
Last active August 1, 2018 05:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikash512/45288a9272ddb5c14ad65023700eced2 to your computer and use it in GitHub Desktop.
Save vikash512/45288a9272ddb5c14ad65023700eced2 to your computer and use it in GitHub Desktop.
Pretty print for sklearn confusion matrix
from sklearn.metrics import confusion_matrix
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels]+[5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print " " + empty_cell,
for label in labels:
print "%{0}s".format(columnwidth) % label,
print
# Print rows
for i, label1 in enumerate(labels):
print " %{0}s".format(columnwidth) % label1,
for j in range(len(labels)):
cell = "%{0}.1f".format(columnwidth) % cm[i, j]
if hide_zeroes:
cell = cell if float(cm[i, j]) != 0 else empty_cell
if hide_diagonal:
cell = cell if i != j else empty_cell
if hide_threshold:
cell = cell if cm[i, j] > hide_threshold else empty_cell
print cell,
print
# first generate with specified labels
labels = [ ... ]
cm = confusion_matrix(ypred, y, labels)
# then print it in a pretty way
print_cm(cm, labels)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment