<jupyter_start><jupyter_text>Tensors all the way down> Discovering an optimised alternative to numpy arrays that are used from the ground up when you train deep learning models- toc:true- branch: master- badges: true- comments: true- author: <NAME>- image: images/tensor.png- categories: [pytorch, fastai, computervision]<jupyter_code>#collapse-hide
#!pip install -Uqq fastbook
#!pip install fastai
import fastbook
fastbook.setup_book()

from fastai.vision.all import *
from fastbook import *

matplotlib.rc('image', cmap='Greys')<jupyter_output><empty_output><jupyter_text>In chapter 4 of the book, we start to really get into what's going on under the hood with deep learning. Turns out, tensors are a pretty important piece. We are still in the realm of computer vision, and we are going to work on distinguishing between handwritten digits.First we use the `untar_data` function to grab a sample of data from the famous MNIST data set. This function returns the path where that data was stored locally.<jupyter_code>path = untar_data(URLs.MNIST_SAMPLE)
Path.BASE_PATH = path
path<jupyter_output><empty_output><jupyter_text>Now we want to briefly inspect the contents of one of our training data folders. This is for the number 7. You can see that it's just a series of .png image files.<jupyter_code>threes_dir = (path/'train/3').ls().sorted()
sevens_dir = (path/'train/7').ls().sorted()
sevens_dir<jupyter_output><empty_output><jupyter_text>In order to look at a single image, we can just open it using `Image.open` which comes from the Python Image Library (PIL).<jupyter_code>im3_path = threes_dir[1]
im3 = Image.open(im3_path)
im3<jupyter_output><empty_output><jupyter_text>Jupyter knows how to display various files, so we can see that image above. But what exactly is an image made up of? If we turn that image into an array, or to a tensor (the next two cells), slicing them so you aren't just seeing zeros on the edges, then you can see that these images are made up of a matrix of values from 0 to 255.<jupyter_code>im3_arr = array(im3)[4:10, 4:10]
im3_arr
im3_tns = tensor(im3)[4:10, 4:10]
im3_tns<jupyter_output><empty_output><jupyter_text>We can use the `show_image` function to turn those 0-255 values back into an image, like so:<jupyter_code>show_image(im3_arr)<jupyter_output><empty_output><jupyter_text>A really nice way of visualising exactly what is going on is to turn this image into a pandas dataframe and then for every individual pixel value, use that value as the background gradient for that cell. Here's an example of part of an image of a handwritten number 3.<jupyter_code>im3_t = tensor(im3)
df = pd.DataFrame(im3_t[4:15,4:22])
df.style.set_properties(**{'font-size':'6pt'}).background_gradient('Greys')<jupyter_output><empty_output><jupyter_text>So now we have a toolkit of ways to view the pixel values that make up an image. We also have a mental model for how we can think about images and how computers represent those images stored on our machine.But how might we then best go about knowing whether a particular image is a 3, let's say, or a 7?One naive approach might be just to get the average value for each individual pixel for all of the threes in our training data, and then just compare the difference between our sample image and this average representation.Let's try that now. Getting the average values for our imagesWe'll set up two lists with images of the digits converted to tensors. You can see that we have 6131 images in our 'threes' list.<jupyter_code>threes_tensors = [tensor(Image.open(i)) for i in threes_dir]
sevens_tensors = [tensor(Image.open(i)) for i in sevens_dir]
len(threes_tensors)<jupyter_output><empty_output><jupyter_text>We can view an individual image, as before, with the `show_image` function:<jupyter_code>show_image(threes_tensors[3])<jupyter_output><empty_output><jupyter_text>Now in order to get the average values for each pixels, we can use the `stack` method to handle the first part of this.Think of it as basically adding an extra dimension to your data structure, such that you have a 'stack' (it's a useful mental image) of those images.<jupyter_code>threes_stack = torch.stack(threes_tensors)<jupyter_output><empty_output><jupyter_text>If we look at the `shape` of our Pytorch stack now, we can see we have our 28x28 image, but we have a stack of 6131 of them.<jupyter_code>threes_stack.shape<jupyter_output><empty_output><jupyter_text>Each individual image is still a tensor:<jupyter_code>a_three = threes_stack[3][4:16, 4:16]
a_three<jupyter_output><empty_output><jupyter_text>Generally speaking, for some operations (like getting the mean average) we're going to want to convert the values to floats, and it also makes sense to normalise the values at the same time. Instead of having a range of 0-255, we want a range of 0-1.<jupyter_code>threes_stack[3][4:16, 4:16].float()/255<jupyter_output><empty_output><jupyter_text>Now that we've done it for a single image, we can perform the same operations on our whole Pytorch stack.<jupyter_code>threes_stack = torch.stack(threes_tensors).float()/255
sevens_stack = torch.stack(sevens_tensors).float()/255
threes_stack.shape # it's good to keep in touch with the shape of our stack<jupyter_output><empty_output><jupyter_text>Now we're getting closer to our desired result. We can squash the stack down into just two dimensions with a simple call to `.mean(0)`, where `0` is the index value of the dimension through which we want to calculate the mean. You'll see now that the `shape` property of our `threes_means` variable is simply a 28x28 image.<jupyter_code>threes_means = threes_stack.mean(0)
threes_means.shape<jupyter_output><empty_output><jupyter_text>When we show that image, you'll see that it's a sort of blurry 'ideal' version of a three<jupyter_code>show_image(threes_means)<jupyter_output><empty_output><jupyter_text>We can do the same for the sevens:<jupyter_code>sevens_means = sevens_stack.mean(0)
show_image(sevens_means)<jupyter_output><empty_output><jupyter_text>Validation: Comparing our average three with a specific threeNow we have our average values, we want to compare these with a single specific digit image. We'll get the difference between those values and whichever difference is the smallest will most likely be the best answer.Our averaged three is still `threes_means` and we can get a single three from our validation set like this:<jupyter_code>threes_dir_validation = (path/'valid/3').ls().sorted()
sevens_dir_validation = (path/'valid/7').ls().sorted()

im3_validation_path = threes_dir_validation[5]
im3_validation = tensor(Image.open(im3_validation_path)).float()/255

im7_validation_path = sevens_dir_validation[3]
im7_validation = tensor(Image.open(im7_validation_path)).float()/255

show_image(im3_validation)
show_image(im7_validation)<jupyter_output><empty_output><jupyter_text>> Note: Calculating the difference between two objects We can use two different measurements of the difference between our mean value and the individual image:- mean absolute difference (calculated by taking the mean of the absolute difference between the two tensor values). Also known as the L1 Norm.- root mean squared error (calculated by first squaring the difference between the two tensor values, taking the mean and then square rooting those values). Also known as the L2 Norm.The second option, the RMSE, gives a stronger signal, you might say, for the differences because you are taking the averages from the squared values. Squaring the difference also takes care of any negative values you might have.<jupyter_code>mean_absolute_difference_3 = (im3_validation - threes_means).abs().mean()
root_mean_squared_error_3 = ((im3_validation - threes_means)**2).mean().sqrt()
mean_absolute_difference_3, root_mean_squared_error_3
mean_absolute_difference_7 = (im7_validation - threes_means).abs().mean()
root_mean_squared_error_7 = ((im7_validation - threes_means)**2).mean().sqrt()
mean_absolute_difference_7, root_mean_squared_error_7<jupyter_output><empty_output><jupyter_text>We can now see that our individual three image is indeed closer to the `threes_means` composite image than to the `sevens_means` composite image. A smaller value at this point is what we're looking for, and the threes have it. It turns out that there is another way to calculate the difference that's built in to Pytorch as loss functions:<jupyter_code>F.l1_loss(im3_validation, threes_means), F.mse_loss(im3_validation, threes_means).sqrt()<jupyter_output><empty_output><jupyter_text>It's a bit more concise, though it does obscure what's going on under the hood in terms of calculations.  Results of the naive approachSo this tells us that our single three is closer to an ideal 3 than an ideal 7, which is great since it reflects the ground truth of our problem. But can we get a metric to know how well we perform on average against a large number of threes and sevens from our validation set?Yes, since we have that dataset ready for use!<jupyter_code>valid_3_tens = torch.stack([tensor(Image.open(o)) for o in (path/'valid'/'3').ls()]).float()/255
valid_7_tens = torch.stack([tensor(Image.open(o)) for o in (path/'valid'/'7').ls()]).float()/255
valid_3_tens.shape, valid_7_tens.shape<jupyter_output><empty_output><jupyter_text>Now we can write a helper function that will allow us to calculate the distance between two images. We use the RMSE or L1 Norm for this difference calculation:<jupyter_code>def mnist_distance(a, b):
    return (a - b).abs().mean((-1, -2))<jupyter_output><empty_output><jupyter_text>We can use this function on our previous example:<jupyter_code>mnist_distance(im3_validation, threes_means)<jupyter_output><empty_output><jupyter_text>We can continue onwards by comparing the rank 3 tensor with the rank 2 tensor. This brings a concept called 'broadcasting' into play.We are comparing a tensor with 2 dimensions with a tensor with 3 dimensions, so Pytorch behaves as if both tensors have three dimensions, and (without taking extra memory) pretends as if there are multiple copies of the image in 2 dimensions. This effectively makes it as if we're comparing two 3-dimensional tensors.From this next calculation, we see returned back a collection of the distances between all of the validation images.<jupyter_code>mnist_distance(valid_3_tens, threes_means)<jupyter_output><empty_output><jupyter_text>In order to check whether an image is a 3, we basically need to know whether the difference for the number 3 is larger than the difference for the number 7.We can write a helper function for that:<jupyter_code>def is_3(img):
    return mnist_distance(img, threes_means) < mnist_distance(img, sevens_means)<jupyter_output><empty_output><jupyter_text>We can now check our ground truth examples:<jupyter_code>is_3(im3_validation), is_3(im7_validation)<jupyter_output><empty_output><jupyter_text>That's what we expected to happen. Our 3 image is a 3, and our 7 image is not a 3. If we want to check the distance in general for our validation set, we have to convert them into floats and then get the mean, but it's really easy. Again, this uses broadcasting:<jupyter_code>validation_accuracy_3 = is_3(valid_3_tens).float().mean()
validation_accuracy_7 = 1 - is_3(valid_7_tens).float().mean()
validation_accuracy_3, validation_accuracy_7<jupyter_output><empty_output><jupyter_text>Overall, then, we can calculate how good our toy or baseline model is for the entire problem:<jupyter_code>(validation_accuracy_3 + validation_accuracy_7) / 2<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07538341564855731, 'fraction_numerical': 0.016029806775842648, 'mean_word_length': 6.231829573934837, 'pattern_counts': {'":': 0, '<': 115, '<?xml version=': 0, '>': 116, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '28', 'dir': 'jupyter-structured-clean-dedup', 'id': '595697', 'license': 'Apache-2.0', 'n_tokens_mistral': 3618, 'n_tokens_neox': 3435, 'n_words': 1376, 'path': '_notebooks/2021-09-16-ch4-tensors.ipynb', 'repo_name': 'strickvl/ml-blog', 'size': '11561'}