#!/usr/bin/env python
# coding: utf-8
#
#
# # 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, comet_ml (you may want to do this slightly differently on your computer):
# In[ ]:
get_ipython().run_line_magic('pip', 'install --upgrade --upgrade-strategy eager --user comet_ml')
# And now tensorflow, keras, and numpy:
# In[ ]:
get_ipython().run_line_magic('pip', 'install --upgrade --upgrade-strategy eager --user 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.
# ### Comet Configuration
# To run the following experiments, you'll need to set your COMET_API_KEY. The easiest way to to this is to set the values in a cell like this:
#
# ```python
# import comet_ml
#
# comet_ml.config.save(api_key="...")
# ```
# where you replace the ...'s with your key.
#
# You can get your COMET_API_KEY under your quickstart link (replace YOUR_USERNAME with your Comet.ml username):
#
# https://www.comet.ml/YOUR_USERNAME/quickstart
#
#
# ## Example 1: Simple Confusion Matrix
#
# First, we will create an experiment:
# In[3]:
from comet_ml import Experiment
# We're not interested at the moment in logging environment details or the code and related items, so I'll not log those:
# In[4]:
experiment = Experiment(project_name="confusion-matrix", log_env_details=False, log_code=False)
# As a simple example, let's consider that we have these six patterns that are our output targets (desired output):
# In[5]:
desired_output = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]
# 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.
#
# 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](http://www.cse.unsw.edu.au/~billw/cs9444/crossentropy.html) which would make the sum of values closer to 1. That might be desirable, but is not required for our example here.
# In[6]:
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[7]:
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[8]:
experiment.end()
# In[9]:
experiment.display(tab="confusion-matrices")
# For more details on this tab, please see the details on the [Confusion Matrix user interface](https://www.comet.ml/docs/user-interface/#confusion-matrices-tab).
# ## 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[10]:
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[11]:
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[12]:
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[13]:
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[14]:
experiment = Experiment(project_name="confusion-matrix", log_env_details=False, log_code=False)
# 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[15]:
model = create_model()
y_predicted = model.predict(x_test)
# We also supply the step (zero, before training), a title, and file_name:
# In[16]:
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[17]:
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),
)
# In[18]:
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.
# In[19]:
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.
# To create an example for each item, we write an `index_to_example` function that takes an index position (offset into the training data), create and log an image, and then return the `assetId` as a key in a dict:
# In[20]:
def index_to_example(index):
image_array = x_test[index]
image_name = "confusion-matrix-%05d.png" % index
results = experiment.log_image(
image_array, name=image_name, image_shape=(28, 28, 1)
)
# Return sample, assetId (index is added automatically)
return {"sample": image_name, "assetId": results["imageId"]}
# 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 = Experiment(project_name="confusion-matrix", log_env_details=False, log_code=False)
# 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,
index_to_example_function=index_to_example,
);
# 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),
index_to_example_function=index_to_example,
)
# 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),
)
# In[26]:
experiment.end()
# 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.
#
# For this, we will create a `ConfusionMatrix` instance and re-use it.
# In[28]:
from comet_ml import ConfusionMatrix
# We create a callback, like, before; however, this time we will keep track of an instance of the `ConfusionMatrix`:
# In[29]:
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)
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[30]:
experiment = Experiment(project_name="confusion-matrix", log_env_details=False, log_code=False)
# And another model:
# In[31]:
model = create_model()
# Again, before training, we log the confusion matrix:
# In[32]:
# Before any training:
y_predicted = model.predict(x_test)
# First, we make an instance, passing in the `index_to_example` function:
# In[33]:
confusion_matrix = ConfusionMatrix(index_to_example_function=index_to_example)
# Now, we use the `comet_matrix` method of the `ConfusionMatrix` class:
# In[34]:
confusion_matrix.compute_matrix(y_test, y_predicted)
# We can use the `ConfusionMatrix` instance to see a rough ASCII version:
# In[35]:
confusion_matrix.display()
# This time, instead of logging the actual and predicted vectors, we instead pass in the entire ConfusionMatrix as the matrix:
# In[36]:
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[37]:
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):
# In[38]:
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):
# In[39]:
experiment.display(tab="confusion-matrices")
# In the `index_to_example` function you can return:
#
# * an integer, representing the index
# * a string, representing text to show in the Example View
# * an URL, representing a link to show in the Example View
# * a `{"sample": NAME, "assetId": ASSET-ID}` dictionary, representing an image asset
# 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[40]:
from comet_ml import ConfusionMatrix
# The heart of the solution is to change how we map indices to examples. Since we want to map all of the instances of one class to a single example, when we encounter an new example, we map all of them at once.
#
# In the constructor, we grab all of the labels for all of the patterns. We then override `_put_example_in_cache()` to do the mapping.
# In[41]:
class MyConfusionMatrix(ConfusionMatrix):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.my_labels = self.winner_function(y_test)
def _put_example_in_cache(self, index, example):
# first, we find all of the items in the same set as index:
this_label = self.my_labels[index]
index_set = [index for (index, label) in enumerate(self.my_labels) if label == this_label]
for key in index_set:
self._cache_example[key] = example
# Everything else is the same:
# In[42]:
experiment = Experiment(project_name="confusion-matrix", log_env_details=False, log_code=False)
# And another model:
# In[43]:
model = create_model()
# Again, before training, we log the confusion matrix:
# In[44]:
# Before any training:
y_predicted = model.predict(x_test)
# First, we make an instance, passing in the `index_to_example` function:
# In[45]:
confusion_matrix = MyConfusionMatrix(index_to_example_function=index_to_example)
# Now, we use the `comet_matrix` method of the `ConfusionMatrix` class:
# In[46]:
confusion_matrix.compute_matrix(y_test, y_predicted)
# We can use the `MyConfusionMatrix` instance to see a rough ASCII version:
# In[47]:
confusion_matrix.display()
# This time, instead of logging the actual and predicted vectors, we instead pass in the entire `MyConfusionMatrix` as the matrix:
# In[48]:
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[49]:
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):
# In[50]:
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):
# In[51]:
experiment.display(tab="confusion-matrices")
# Note that each cell has up to 25 examples, but they are all the same. We could have used `max_examples_per_cell=1` to show only the single set image.
# ## 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](https://github.com/comet-ml/issue-tracking) and leave us a note.