Comet.ml Confusion Matrix¶
This page is available as an executable or viewable Jupyter Notebook:
Comet.ml can generate a variety of visualizations, including line charts, scatter charts, bar charts, and histograms. This notebook explores Comet's confusion matrix chart.
Setup¶
The first thing we'll do in this notebook tutorial is install comet_ml and other items that we'll need for this demonstration. That will include keras, tensorflow, and numpy.
First, install comet_ml (you may want to do this slightly differently on your computer):
%pip install --upgrade comet_ml>=3.10.0
And now tensorflow, keras, and numpy:
%pip install keras tensorflow numpy
As the output may suggest, if anything got updated, it might be a good idea to restart the kernel and continue from here (should not be required on Google's colab).
Import comet_ml¶
To run the following experiments, you'll need to import comet_ml, and have your Comet API key configured.
import comet_ml
comet_ml.init()
Example 1: Simple Confusion Matrix¶
First, we will create an experiment:
experiment = comet_ml.Experiment(
project_name="confusion-matrix",
)
As a simple example, let's consider that we have these six patterns that are our output targets (desired output):
desired_output = [0, 1, 2, 0, 1, 2]
Imagine that this is a classification task where each target (desired output) is composed of three output values, with one unit "on" (set to 1) and the others "off" (set to 0). This is sometimes called a "one-hot" representation and is a common way of representing categories. There are 6 patterns, where there are 2 each for category.
In the above representation, we use "labels" to identify the correct classification, but we could have easily have used the one-hot representation as well:
desired_output = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]
Now, let's make up some sample data that an model might produce. Let's say initially that the output is pretty random and doesn't even add up to 1 for each row. This may be unrealistic as many such classification tasks might use an error/loss output metric that is based on cross entropy which would make the sum of values closer to 1. That might be desirable, but is not required for our example here.
actual_output = [
[0.1, 0.5, 0.4],
[0.2, 0.2, 0.3],
[0.7, 0.4, 0.5],
[0.3, 0.8, 0.3],
[0.0, 0.5, 0.3],
[0.1, 0.5, 0.5],
]
Our goal now is to visualize how much the model mixes up the categories. That is, we'd like to see the Confusion Matrix comparing all categories against each other. We can do that easily by simply logging it with the experiment:
experiment.log_confusion_matrix(desired_output, actual_output);
That's it! We can now end the experiment and take a look at the resulting matrix:
experiment.end()
experiment.display(tab="confusion-matrices")
For more details on this tab, please see the details on the Confusion Matrix user interface.
Example #2: Log Confusion Matrices During Learning¶
This example will create a series of confusion matrices showing how the model gets less confused as training proceeds.
We will train the standard MNIST digit classification task.
We import the items that we will need:
from tensorflow.keras.callbacks import Callback
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import to_categorical
from keras.datasets import mnist
We load the training set:
num_classes = 10
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
# convert class vectors to binary class matrices
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
Define a function to create the model:
def create_model():
model = Sequential()
model.add(Dense(128, activation="sigmoid", input_shape=(784,)))
model.add(Dense(128, activation="sigmoid"))
model.add(Dense(128, activation="sigmoid"))
model.add(Dense(10, activation="softmax"))
model.compile(
loss="categorical_crossentropy", optimizer=RMSprop(), metrics=["accuracy"]
)
return model
Next, we define a Keras callback to log the confusion matrix:
class ConfusionMatrixCallback(Callback):
def __init__(self, experiment, inputs, targets):
self.experiment = experiment
self.inputs = inputs
self.targets = targets
def on_epoch_end(self, epoch, logs={}):
predicted = self.model.predict(self.inputs)
self.experiment.log_confusion_matrix(
self.targets,
predicted,
title="Confusion Matrix, Epoch #%d" % (epoch + 1),
file_name="confusion-matrix-%03d.json" % (epoch + 1),
)
And create another Comet experiment:
experiment = comet_ml.Experiment(
project_name="confusion-matrix",
)
Before any training, we want to log the confusion so that we can see what it looks like before any adjusting of weights in the network:
model = create_model()
y_predicted = model.predict(x_test)
We also supply the step (zero, before training), a title, and file_name:
experiment.log_confusion_matrix(
y_test,
y_predicted,
step=0,
title="Confusion Matrix, Epoch #0",
file_name="confusion-matrix-%03d.json" % 0,
);
We now create the callback and train the data for 5 epochs:
callback = ConfusionMatrixCallback(experiment, x_test, y_test)
model.fit(
x_train,
y_train,
batch_size=120,
epochs=5,
callbacks=[callback],
validation_data=(x_test, y_test),
)
experiment.end()
Now we take a look at the matrices created over the training. You can switch between confusion matrices by selecting the name in the upper, left-hand corner.
experiment.display(tab="confusion-matrices")
Example 3: Create Images for Each Sample¶
For this example, we will create images for each example, up to 25 examples per cell.
We'll do the same steps as above:
- create an experiment
- create the model
- log inital confusion
- create a callback
- train the model
- display the experiment
experiment = comet_ml.Experiment(
project_name="confusion-matrix",
)
model = create_model()
y_predicted = model.predict(x_test)
experiment.log_confusion_matrix(
y_test,
y_predicted,
step=0,
title="Confusion Matrix, Epoch #0",
file_name="confusion-matrix-%03d.json" % 0,
images=x_test,
image_shape=(28, 28),
);
class ConfusionMatrixCallbackWithImages(Callback):
def __init__(self, experiment, inputs, targets):
self.experiment = experiment
self.inputs = inputs
self.targets = targets
def on_epoch_end(self, epoch, logs={}):
predicted = self.model.predict(self.inputs)
self.experiment.log_confusion_matrix(
self.targets,
predicted,
title="Confusion Matrix, Epoch #%d" % (epoch + 1),
file_name="confusion-matrix-%03d.json" % (epoch + 1),
images=self.inputs,
image_shape=(28, 28),
)
Now we'll train as before.
NOTE: this takes a lot longer than before, but we'll see how to speed this up in the next example.
callback = ConfusionMatrixCallbackWithImages(experiment, x_test, y_test)
model.fit(
x_train,
y_train,
batch_size=120,
epochs=5,
callbacks=[callback],
validation_data=(x_test, y_test),
)
experiment.end()
experiment.display(tab="confusion-matrices")
What is very nice about this is that if you click on a cell, you can see examples of the types of digits that fall into this group. For example if you click in the cell counting the confusion between 8's and 0's you'll see a sample of exactly which of those images.
However, there is a large issue with this example. Looking at the summary above, you can see that many thousands of images were uploaded. In addition, if you explore the confusion matrices over the course of learning, you'll see different examples for every epoch. The next example fixes that issue.
Example 4: Reuse ConfusionMatrix instance¶
Now, we want to create example images for each of the cells in the matrix. In addition, we want to re-use the images if we can.
We create a callback, like, before; however, this time we will keep track of an instance of the ConfusionMatrix
:
class ConfusionMatrixCallbackReuseImages(Callback):
def __init__(self, experiment, inputs, targets, confusion_matrix):
self.experiment = experiment
self.inputs = inputs
self.targets = targets
self.confusion_matrix = confusion_matrix
def on_epoch_end(self, epoch, logs={}):
predicted = self.model.predict(self.inputs)
self.confusion_matrix.compute_matrix(self.targets, predicted, images=self.inputs)
self.experiment.log_confusion_matrix(
matrix=self.confusion_matrix,
title="Confusion Matrix, Epoch #%d" % (epoch + 1),
file_name="confusion-matrix-%03d.json" % (epoch + 1),
)
We create another Comet experiment:
experiment = comet_ml.Experiment(
project_name="confusion-matrix",
)
And another model:
model = create_model()
Again, before training, we log the confusion matrix:
# Before any training:
y_predicted = model.predict(x_test)
First, we make an instance of the Confusion Matrix for later re-use:
confusion_matrix = experiment.create_confusion_matrix()
Now, we use the comet_matrix
method of the ConfusionMatrix
class:
confusion_matrix.compute_matrix(y_test, y_predicted, images=x_test, image_shape=(28,28))
We can use the ConfusionMatrix.display()
method to see a rough ASCII version:
confusion_matrix.display()
This time, instead of logging the actual and predicted vectors, we instead pass in the entire ConfusionMatrix as the matrix:
experiment.log_confusion_matrix(
matrix=confusion_matrix,
step=0,
title="Confusion Matrix, Epoch #0",
file_name="confusion-matrix-%03d.json" % 0,
);
Again, we create callbacks, and train the network (this will take just a little more time, as it is generating the assets on the fly):
callback = ConfusionMatrixCallbackReuseImages(experiment, x_test, y_test, confusion_matrix)
model.fit(
x_train,
y_train,
batch_size=120,
epochs=5,
callbacks=[callback],
validation_data=(x_test, y_test),
)
We end the experiment (here you can see how many assets were uploaded):
experiment.end()
First, you'll notice that this trained much faster than the previous example, and the number of images was reduced by about 75%. That is becaused we reused the examples in each cell where we can.
See the full confusion matrix, complete with sample images in each cell (click on a cell to see the examples):
experiment.display(tab="confusion-matrices")
The ConfusionMatrix
object allows many options, including:
- automatically finding the "most confused" categories, if more than 25
- limit the categories shown (use
ConfusionMatrix(selected=[...])
) - change the row and column labels
- change the category labels
- change the title
- display text, URLs, or images in Example View
Example 5: Using Sets of Examples¶
Now, we'll use one image for a set of examples. Before we assumed that there was one image for each index. We change that assumption to use one image for a set.
To do this, we'll subclass the ConfusionMatrix and override the method that caches the images.
from comet_ml import ConfusionMatrix
The heart of the solution is to change how we get the cache key. Since we want to map all of the instances of one class to a single example, when we encounter an new example, we map each category to a single instance.
In the constructor, we grab all of the labels for all of the patterns. We then override the _get_cache_key()
method to change the cache mapping.
class MyConfusionMatrix(ConfusionMatrix):
def __init__(self, y_test, *args, **kwargs):
super().__init__(*args, **kwargs)
self.my_labels = self.winner_function(y_test)
def _get_cache_key(self, index):
key = self.my_labels[index]
return key
Everything else is the same:
experiment = comet_ml.Experiment(
project_name="confusion-matrix",
)
And another model:
model = create_model()
Again, before training, we log the confusion matrix:
# Before any training:
y_predicted = model.predict(x_test)
First, we make an instance, passing in the inputs and experiment:
confusion_matrix = MyConfusionMatrix(y_test, experiment=experiment)
Now, we use the comet_matrix
method of the ConfusionMatrix
class:
confusion_matrix.compute_matrix(y_test, y_predicted, images=x_test, image_shape=(28, 28))
We can use the MyConfusionMatrix
instance to see a rough ASCII version:
confusion_matrix.display()
This time, instead of logging the actual and predicted vectors, we instead pass in the entire MyConfusionMatrix
as the matrix:
experiment.log_confusion_matrix(
matrix=confusion_matrix,
step=0,
title="Confusion Matrix, Epoch #0",
file_name="confusion-matrix-%03d.json" % 0,
);
Again, we create callbacks, and train the network (this will take just a little more time, as it is generating the assets on the fly):
callback = ConfusionMatrixCallbackReuseImages(experiment, x_test, y_test, confusion_matrix)
model.fit(
x_train,
y_train,
batch_size=120,
epochs=5,
callbacks=[callback],
validation_data=(x_test, y_test),
)
We end the experiment (here you can see how many assets were uploaded):
experiment.end()
First, you'll notice that this trained much faster than the previous example, and the number of images was exactly 10. That is becaused we used one image for each image set, and we reused each of those between epochs.
See the full confusion matrix, complete with sample images in each cell (click on a cell to see the examples):
experiment.display(tab="confusion-matrices")
Note that each cell has at most 1 example and every cell in each row uses it.
Conclusion¶
We hope that this gives you some ideas of how you can use the Comet Confusion Matrix! If you have questions or comments, feel free to visit the Comet issue tracker and leave us a note.