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):

In [1]:
%pip install --upgrade comet_ml>=3.10.0

And now tensorflow, keras, and numpy:

In [2]:
%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.

In [3]:
import comet_ml
In [4]:
comet_ml.init()
COMET INFO: Comet API key is valid

Example 1: Simple Confusion Matrix

First, we will create an experiment:

In [5]:
experiment = comet_ml.Experiment(
    project_name="confusion-matrix", 
)
COMET WARNING: As you are running in a Jupyter environment, you will need to call `experiment.end()` when finished to ensure all metrics and code are logged before exiting.
COMET INFO: Experiment is live on comet.ml https://www.comet.ml/dsblank/confusion-matrix/ab5ffc64fc6a47b9bbd2e37d279703cb

As a simple example, let's consider that we have these six patterns that are our output targets (desired output):

In [6]:
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.

In [7]:
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:

In [8]:
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:

In [9]:
experiment.end()
COMET INFO: ---------------------------
COMET INFO: Comet.ml Experiment Summary
COMET INFO: ---------------------------
COMET INFO:   Data:
COMET INFO:     display_summary_level : 1
COMET INFO:     url                   : https://www.comet.ml/dsblank/confusion-matrix/ab5ffc64fc6a47b9bbd2e37d279703cb
COMET INFO:   Uploads:
COMET INFO:     confusion-matrix         : 1
COMET INFO:     environment details      : 1
COMET INFO:     filename                 : 1
COMET INFO:     git metadata             : 1
COMET INFO:     git-patch (uncompressed) : 1 (71 KB)
COMET INFO:     installed packages       : 1
COMET INFO:     notebook                 : 1
COMET INFO:     os packages              : 1
COMET INFO:     source_code              : 1
COMET INFO: ---------------------------
COMET INFO: Uploading metrics, params, and assets to Comet before program termination (may take several seconds)
COMET INFO: The Python SDK has 3600 seconds to finish before aborting...
In [10]:
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:

In [11]:
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:

In [12]:
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:

In [13]:
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:

In [14]:
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:

In [15]:
experiment = comet_ml.Experiment(
    project_name="confusion-matrix", 
)
COMET WARNING: As you are running in a Jupyter environment, you will need to call `experiment.end()` when finished to ensure all metrics and code are logged before exiting.
COMET INFO: Experiment is live on comet.ml https://www.comet.ml/dsblank/confusion-matrix/f1fb7618720c40e5be33b5100ad3b776

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:

In [16]:
model = create_model()

y_predicted = model.predict(x_test)

We also supply the step (zero, before training), a title, and file_name:

In [17]:
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:

In [18]:
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),
)
COMET INFO: Ignoring automatic log_parameter('verbose') because 'keras:verbose' is in COMET_LOGGING_PARAMETERS_IGNORE
Epoch 1/5
500/500 [==============================] - 5s 8ms/step - loss: 1.2974 - accuracy: 0.6097 - val_loss: 0.3082 - val_accuracy: 0.9097
Epoch 2/5
500/500 [==============================] - 3s 7ms/step - loss: 0.2815 - accuracy: 0.9166 - val_loss: 0.2080 - val_accuracy: 0.9372
Epoch 3/5
500/500 [==============================] - 3s 6ms/step - loss: 0.2041 - accuracy: 0.9396 - val_loss: 0.1647 - val_accuracy: 0.9520
Epoch 4/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1431 - accuracy: 0.9574 - val_loss: 0.1349 - val_accuracy: 0.9582
Epoch 5/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1198 - accuracy: 0.9647 - val_loss: 0.1178 - val_accuracy: 0.9638
Out[18]:
<tensorflow.python.keras.callbacks.History at 0x7f211a138430>
In [19]:
experiment.end()
COMET INFO: ---------------------------
COMET INFO: Comet.ml Experiment Summary
COMET INFO: ---------------------------
COMET INFO:   Data:
COMET INFO:     display_summary_level : 1
COMET INFO:     url                   : https://www.comet.ml/dsblank/confusion-matrix/f1fb7618720c40e5be33b5100ad3b776
COMET INFO:   Metrics [count] (min, max):
COMET INFO:     accuracy [5]                 : (0.785966694355011, 0.9656999707221985)
COMET INFO:     batch_accuracy [250]         : (0.06666667014360428, 0.9666666388511658)
COMET INFO:     batch_loss [250]             : (0.11659321188926697, 2.5504069328308105)
COMET INFO:     epoch_duration [5]           : (3.6289265220984817, 5.298398307990283)
COMET INFO:     loss [5]                     : (0.11707635223865509, 0.7549315094947815)
COMET INFO:     val_accuracy [5]             : (0.9096999764442444, 0.9638000130653381)
COMET INFO:     val_loss [5]                 : (0.11783557385206223, 0.3082138001918793)
COMET INFO:     validate_batch_accuracy [45] : (0.8865079283714294, 1.0)
COMET INFO:     validate_batch_loss [45]     : (0.02385331317782402, 0.3838881850242615)
COMET INFO:   Others:
COMET INFO:     trainable_params : 134794
COMET INFO:   Parameters:
COMET INFO:     Optimizer             : RMSprop
COMET INFO:     RMSprop_centered      : 1
COMET INFO:     RMSprop_decay         : 1
COMET INFO:     RMSprop_epsilon       : 1e-07
COMET INFO:     RMSprop_learning_rate : 0.001
COMET INFO:     RMSprop_momentum      : 1
COMET INFO:     RMSprop_name          : RMSprop
COMET INFO:     RMSprop_rho           : 0.9
COMET INFO:     epochs                : 5
COMET INFO:     steps                 : 500
COMET INFO:   Uploads [count]:
COMET INFO:     confusion-matrix [6]     : 6
COMET INFO:     environment details      : 1
COMET INFO:     filename                 : 1
COMET INFO:     git metadata             : 1
COMET INFO:     git-patch (uncompressed) : 1 (71 KB)
COMET INFO:     installed packages       : 1
COMET INFO:     model graph              : 1
COMET INFO:     notebook                 : 1
COMET INFO:     os packages              : 1
COMET INFO:     source_code              : 1
COMET INFO: ---------------------------
COMET INFO: Waiting for completion of the file uploads (may take several seconds)
COMET INFO: The Python SDK has 10800 seconds to finish before aborting...
COMET INFO: Still uploading 3 file(s)

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.

In [20]:
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:

  1. create an experiment
  2. create the model
  3. log inital confusion
  4. create a callback
  5. train the model
  6. display the experiment
In [21]:
experiment = comet_ml.Experiment(
    project_name="confusion-matrix", 
)
COMET WARNING: As you are running in a Jupyter environment, you will need to call `experiment.end()` when finished to ensure all metrics and code are logged before exiting.
COMET INFO: Experiment is live on comet.ml https://www.comet.ml/dsblank/confusion-matrix/ddbe3072aad6417085c070e1ba414945

In [22]:
model = create_model()

y_predicted = model.predict(x_test)
In [23]:
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),
);
In [24]:
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.

In [25]:
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),
)
Epoch 1/5
500/500 [==============================] - 4s 6ms/step - loss: 1.3291 - accuracy: 0.5844 - val_loss: 0.3127 - val_accuracy: 0.9076
Epoch 2/5
500/500 [==============================] - 3s 7ms/step - loss: 0.2766 - accuracy: 0.9190 - val_loss: 0.2006 - val_accuracy: 0.9396
Epoch 3/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1914 - accuracy: 0.9432 - val_loss: 0.1742 - val_accuracy: 0.9479
Epoch 4/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1497 - accuracy: 0.9542 - val_loss: 0.1320 - val_accuracy: 0.9595
Epoch 5/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1245 - accuracy: 0.9630 - val_loss: 0.1183 - val_accuracy: 0.9656
Out[25]:
<tensorflow.python.keras.callbacks.History at 0x7f20d8569100>
In [26]:
experiment.end()
COMET INFO: ---------------------------
COMET INFO: Comet.ml Experiment Summary
COMET INFO: ---------------------------
COMET INFO:   Data:
COMET INFO:     display_summary_level : 1
COMET INFO:     url                   : https://www.comet.ml/dsblank/confusion-matrix/ddbe3072aad6417085c070e1ba414945
COMET INFO:   Metrics [count] (min, max):
COMET INFO:     accuracy [5]                 : (0.7693666815757751, 0.9639833569526672)
COMET INFO:     batch_accuracy [250]         : (0.1037878766655922, 0.9833333492279053)
COMET INFO:     batch_loss [250]             : (0.07256641238927841, 2.432967185974121)
COMET INFO:     epoch_duration [5]           : (31.040708475047722, 39.406505106948316)
COMET INFO:     loss [5]                     : (0.12004319578409195, 0.7886505126953125)
COMET INFO:     val_accuracy [5]             : (0.9075999855995178, 0.9656000137329102)
COMET INFO:     val_loss [5]                 : (0.1183130219578743, 0.31273534893989563)
COMET INFO:     validate_batch_accuracy [45] : (0.8801587224006653, 0.9833333492279053)
COMET INFO:     validate_batch_loss [45]     : (0.04573925957083702, 0.380536288022995)
COMET INFO:   Others:
COMET INFO:     trainable_params : 134794
COMET INFO:   Parameters:
COMET INFO:     Optimizer             : RMSprop
COMET INFO:     RMSprop_centered      : 1
COMET INFO:     RMSprop_decay         : 1
COMET INFO:     RMSprop_epsilon       : 1e-07
COMET INFO:     RMSprop_learning_rate : 0.001
COMET INFO:     RMSprop_momentum      : 1
COMET INFO:     RMSprop_name          : RMSprop
COMET INFO:     RMSprop_rho           : 0.9
COMET INFO:     epochs                : 5
COMET INFO:     steps                 : 500
COMET INFO:   Uploads [count]:
COMET INFO:     confusion-matrix [6]     : 6
COMET INFO:     environment details      : 1
COMET INFO:     filename                 : 1
COMET INFO:     git metadata             : 1
COMET INFO:     git-patch (uncompressed) : 1 (71 KB)
COMET INFO:     images [4026]            : 4026
COMET INFO:     installed packages       : 1
COMET INFO:     model graph              : 1
COMET INFO:     notebook                 : 1
COMET INFO:     os packages              : 1
COMET INFO:     source_code              : 1
COMET INFO: ---------------------------
COMET INFO: Uploading 1 metrics, params and output messages
In [27]:
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:

In [28]:
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:

In [29]:
experiment = comet_ml.Experiment(
    project_name="confusion-matrix", 
)
COMET WARNING: As you are running in a Jupyter environment, you will need to call `experiment.end()` when finished to ensure all metrics and code are logged before exiting.
COMET INFO: Experiment is live on comet.ml https://www.comet.ml/dsblank/confusion-matrix/df5910f0ed5b4a1bbf5929e72bdb1668

And another model:

In [30]:
model = create_model()

Again, before training, we log the confusion matrix:

In [31]:
# Before any training:
y_predicted = model.predict(x_test)

First, we make an instance of the Confusion Matrix for later re-use:

In [32]:
confusion_matrix = experiment.create_confusion_matrix()

Now, we use the comet_matrix method of the ConfusionMatrix class:

In [33]:
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:

In [34]:
confusion_matrix.display()
   A                Confusion Matrix            
   c               Predicted Category           
   t       0   1   2   3   4   5   6   7   8   9
   u   0   0   0   0   0   0   0   0   0   0 980
   a   1   0   0   0   0   0   0   0   0   0 113
   l   2   0   0   0   0   0   0   0   0   0 103
       3   0   0   0   0   0   0   0   0   0 101
   C   4   0   0   0   0   0   0   0   0   0 982
   a   5   0   0   0   0   0   0   0   0   0 892
   t   6   0   0   0   0   0   0   0   0   0 958
   e   7   0   0   0   0   0   0   0   0   0 102
   g   8   0   0   0   0   0   0   0   0   0 974
   o   9   0   0   0   0   0   0   0   0   0 100
   r

This time, instead of logging the actual and predicted vectors, we instead pass in the entire ConfusionMatrix as the matrix:

In [35]:
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):

In [36]:
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),
)
Epoch 1/5
500/500 [==============================] - 4s 6ms/step - loss: 1.3040 - accuracy: 0.6069 - val_loss: 0.3161 - val_accuracy: 0.9086
Epoch 2/5
500/500 [==============================] - 3s 7ms/step - loss: 0.2903 - accuracy: 0.9162 - val_loss: 0.2125 - val_accuracy: 0.9367
Epoch 3/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1964 - accuracy: 0.9419 - val_loss: 0.1614 - val_accuracy: 0.9520
Epoch 4/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1500 - accuracy: 0.9562 - val_loss: 0.1390 - val_accuracy: 0.9590
Epoch 5/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1246 - accuracy: 0.9632 - val_loss: 0.1225 - val_accuracy: 0.9634
Out[36]:
<tensorflow.python.keras.callbacks.History at 0x7f2098753940>

We end the experiment (here you can see how many assets were uploaded):

In [37]:
experiment.end()
COMET INFO: ---------------------------
COMET INFO: Comet.ml Experiment Summary
COMET INFO: ---------------------------
COMET INFO:   Data:
COMET INFO:     display_summary_level : 1
COMET INFO:     url                   : https://www.comet.ml/dsblank/confusion-matrix/df5910f0ed5b4a1bbf5929e72bdb1668
COMET INFO:   Metrics [count] (min, max):
COMET INFO:     accuracy [5]                 : (0.7788000106811523, 0.9639666676521301)
COMET INFO:     batch_accuracy [250]         : (0.11666666716337204, 0.9750000238418579)
COMET INFO:     batch_loss [250]             : (0.10746046900749207, 2.4073240756988525)
COMET INFO:     epoch_duration [5]           : (3.8023373920004815, 31.354876097058877)
COMET INFO:     loss [5]                     : (0.12115586549043655, 0.773209810256958)
COMET INFO:     val_accuracy [5]             : (0.9085999727249146, 0.9634000062942505)
COMET INFO:     val_loss [5]                 : (0.1224675327539444, 0.31605249643325806)
COMET INFO:     validate_batch_accuracy [45] : (0.8857723474502563, 1.0)
COMET INFO:     validate_batch_loss [45]     : (0.042409297078847885, 0.38421693444252014)
COMET INFO:   Others:
COMET INFO:     trainable_params : 134794
COMET INFO:   Parameters:
COMET INFO:     Optimizer             : RMSprop
COMET INFO:     RMSprop_centered      : 1
COMET INFO:     RMSprop_decay         : 1
COMET INFO:     RMSprop_epsilon       : 1e-07
COMET INFO:     RMSprop_learning_rate : 0.001
COMET INFO:     RMSprop_momentum      : 1
COMET INFO:     RMSprop_name          : RMSprop
COMET INFO:     RMSprop_rho           : 0.9
COMET INFO:     epochs                : 5
COMET INFO:     steps                 : 500
COMET INFO:   Uploads [count]:
COMET INFO:     confusion-matrix [6]     : 6
COMET INFO:     environment details      : 1
COMET INFO:     filename                 : 1
COMET INFO:     git metadata             : 1
COMET INFO:     git-patch (uncompressed) : 1 (45 KB)
COMET INFO:     images [1180]            : 1180
COMET INFO:     installed packages       : 1
COMET INFO:     model graph              : 1
COMET INFO:     notebook                 : 1
COMET INFO:     os packages              : 1
COMET INFO:     source_code              : 1
COMET INFO: ---------------------------
COMET INFO: Uploading 1 metrics, params and output messages

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):

In [38]:
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.

In [39]:
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.

In [40]:
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:

In [41]:
experiment = comet_ml.Experiment(
    project_name="confusion-matrix", 
)
COMET WARNING: As you are running in a Jupyter environment, you will need to call `experiment.end()` when finished to ensure all metrics and code are logged before exiting.
COMET INFO: Experiment is live on comet.ml https://www.comet.ml/dsblank/confusion-matrix/2add2f772a264dfc895804eaa2119e0f

And another model:

In [42]:
model = create_model()

Again, before training, we log the confusion matrix:

In [43]:
# Before any training:
y_predicted = model.predict(x_test)

First, we make an instance, passing in the inputs and experiment:

In [44]:
confusion_matrix = MyConfusionMatrix(y_test, experiment=experiment)

Now, we use the comet_matrix method of the ConfusionMatrix class:

In [45]:
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:

In [46]:
confusion_matrix.display()
   A                Confusion Matrix            
   c               Predicted Category           
   t       0   1   2   3   4   5   6   7   8   9
   u   0   0   0   0   0   0   0   0   0 980   0
   a   1   0   0   0   0   0   0   0   0 113   0
   l   2   0   0   0   0   0   0   0   0 103   0
       3   0   0   0   0   0   0   0   0 101   0
   C   4   0   0   0   0   0   0   0   0 982   0
   a   5   0   0   0   0   0   0   0   0 892   0
   t   6   0   0   0   0   0   0   0   0 958   0
   e   7   0   0   0   0   0   0   0   0 102   0
   g   8   0   0   0   0   0   0   0   0 974   0
   o   9   0   0   0   0   0   0   0   0 100   0
   r

This time, instead of logging the actual and predicted vectors, we instead pass in the entire MyConfusionMatrix as the matrix:

In [47]:
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):

In [48]:
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),
)
Epoch 1/5
500/500 [==============================] - 4s 6ms/step - loss: 1.3133 - accuracy: 0.6074 - val_loss: 0.2965 - val_accuracy: 0.9157
Epoch 2/5
500/500 [==============================] - 3s 6ms/step - loss: 0.2788 - accuracy: 0.9174 - val_loss: 0.2104 - val_accuracy: 0.9383
Epoch 3/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1971 - accuracy: 0.9403 - val_loss: 0.1759 - val_accuracy: 0.9478
Epoch 4/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1539 - accuracy: 0.9539 - val_loss: 0.1387 - val_accuracy: 0.9594
Epoch 5/5
500/500 [==============================] - 3s 6ms/step - loss: 0.1281 - accuracy: 0.9619 - val_loss: 0.1298 - val_accuracy: 0.9614
Out[48]:
<tensorflow.python.keras.callbacks.History at 0x7f210d801370>

We end the experiment (here you can see how many assets were uploaded):

In [49]:
experiment.end()
COMET INFO: ---------------------------
COMET INFO: Comet.ml Experiment Summary
COMET INFO: ---------------------------
COMET INFO:   Data:
COMET INFO:     display_summary_level : 1
COMET INFO:     url                   : https://www.comet.ml/dsblank/confusion-matrix/2add2f772a264dfc895804eaa2119e0f
COMET INFO:   Metrics [count] (min, max):
COMET INFO:     accuracy [5]                 : (0.7863666415214539, 0.9636499881744385)
COMET INFO:     batch_accuracy [250]         : (0.10000000149011612, 0.9666666388511658)
COMET INFO:     batch_loss [250]             : (0.12279674410820007, 2.3612191677093506)
COMET INFO:     epoch_duration [5]           : (3.4647893810179085, 4.589158504968509)
COMET INFO:     loss [5]                     : (0.12284887582063675, 0.7659122943878174)
COMET INFO:     val_accuracy [5]             : (0.9157000184059143, 0.9613999724388123)
COMET INFO:     val_loss [5]                 : (0.1298353374004364, 0.296523779630661)
COMET INFO:     validate_batch_accuracy [45] : (0.8918699026107788, 1.0)
COMET INFO:     validate_batch_loss [45]     : (0.03404945880174637, 0.3674503266811371)
COMET INFO:   Others:
COMET INFO:     trainable_params : 134794
COMET INFO:   Parameters:
COMET INFO:     Optimizer             : RMSprop
COMET INFO:     RMSprop_centered      : 1
COMET INFO:     RMSprop_decay         : 1
COMET INFO:     RMSprop_epsilon       : 1e-07
COMET INFO:     RMSprop_learning_rate : 0.001
COMET INFO:     RMSprop_momentum      : 1
COMET INFO:     RMSprop_name          : RMSprop
COMET INFO:     RMSprop_rho           : 0.9
COMET INFO:     epochs                : 5
COMET INFO:     steps                 : 500
COMET INFO:   Uploads [count]:
COMET INFO:     confusion-matrix [6]     : 6
COMET INFO:     environment details      : 1
COMET INFO:     filename                 : 1
COMET INFO:     git metadata             : 1
COMET INFO:     git-patch (uncompressed) : 1 (45 KB)
COMET INFO:     images [10]              : 10
COMET INFO:     installed packages       : 1
COMET INFO:     model graph              : 1
COMET INFO:     notebook                 : 1
COMET INFO:     os packages              : 1
COMET INFO:     source_code              : 1
COMET INFO: ---------------------------
COMET INFO: Uploading 1 metrics, params and output messages

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):

In [50]:
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.