Skip to content

Instantly share code, notes, and snippets.

@ola0x
Created January 17, 2021 00:24
Show Gist options
  • Save ola0x/9ccff9d331b9e6d3da5d390c3a9f5690 to your computer and use it in GitHub Desktop.
Save ola0x/9ccff9d331b9e6d3da5d390c3a9f5690 to your computer and use it in GitHub Desktop.
How to plot confusion matrix using Tensor Flow model maker
%matplotlib inline
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import image_classifier
predicts = model.predict_top_k(test_data)
y_pred = []
y_true = []
for i, (image, label) in enumerate(test_data.gen_dataset().unbatch().take(100)):
pred_label = predicts[i][0][0]
true_label = test_data.index_to_label[label.numpy()]
y_pred.append(pred_label)
y_true.append(true_label)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
classes = test_data.index_to_label
cm = confusion_matrix(y_true=y_true, y_pred=y_pred)
plot_confusion_matrix(cm=cm, classes=classes, title='Confusion Matrix')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment