Recently I did some work on creating a system to identify handwritten numbers using only basic math.

Below are my results

```
#hide
from fastai.vision.all import *
from utils import *
matplotlib.rc('image', cmap='Greys')
```

```
path = untar_data('https://s3.amazonaws.com/fast-ai-imageclas/mnist_png.tgz')
```

## Handwritten number recognition without Machine Learning¶

TLDR: creating image recognition using only simple math and understanding how different error formulas affect results.

While looking at the latest update to FastAi, Jeremy Howard encourages people that before starting to work on a machine learning solution, to try and build a non ML baseline solution first, so that you can evaluate your final model performance against. He demonstrated using the MNIST dataset which is thousands of hand written digits scanned and labled, and was one of the early datasets used for computer vision. His version just used the scanned 3s and 7s as an example and get a 90% accuracy rate at telling them apart. This is interesting, however, it's clear that if the only posibilities are 3 or 7, that limits the scope for error of mislableing. I wanted to try and expand this across all of the digits, to find out what sort of accuracy rate was possible and also what digits were the hardest to tell apart, and where the largest area of mislabling was and then to see if this applied also to the machine learning model.

```
#hide
Path.BASE_PATH = path
```

I'm not going to go into too much of the detail here as it's covered in the course content, but basically for each of the images we're needing to:

- get a list of all the image files on disk - these are all greyscale png files of 28x28 pixels
- load each image file into a 2d PyTorch Tensor (a specialised array optimized for GPU batch calculations)
- combine all the tensors into a single stacked tensor, where the first demension indicates the image number
- for each pixel in the original image size, create the mean of all of the values of all of the images - that is create the avg for all of the other values of that character

repeat this for both the training set and testing set images. I'm returning lists containing outputs for each of tese steps as I can never decide to throw anything away as we might (just) need it right??

```
def load_chars(digit,set_name):
files = (path/set_name/str(digit)).ls().sorted()
img_tensors = [tensor(Image.open(f)).float() for f in files]
stacked_tensors = torch.stack(img_tensors)
img_mean = stacked_tensors.mean(0)
return [digit,img_mean,stacked_tensors,img_tensors,files]
```

```
def load_sets(digit):
training = load_chars(digit,'training')
testing = load_chars(digit,'testing')
return [training,testing]
```

```
%time all_digits = [load_sets(i) for i in range(10)]
```

```
all_means = [ i[0][1] for i in all_digits]
training_img_counts = [ len(i[0][2]) for i in all_digits]
```

## Looking at our data¶

It's helpful to start by visualising our data and making an initial judgement as to strengths and limitations of our data set. Below are the calculated mean images for the training and test set respectively.

Straight away we can say:

- the testing set looks to be representative of the training set
- the digits look to be very uniform - there doesn't seem to be examples of 7s with a crossbar, 4s with a closed top, or 1s with a horizontal serif at the top or bottom

with this in mind, we shouldn't expect this to generalize very well if our production model will contain these sorts of differences. This is called out of domain data.

```
show_images(all_means,titles=training_img_counts)
```

The figures above show the mean of all the images, and the number above is the number of images included within the set for the training set. Lets do the same with the testing (validation) set that the data has already been presplit into.

```
all_testing_means = [ i[1][1] for i in all_digits]
testing_img_counts = [ len(i[1][2]) for i in all_digits]
show_images(all_testing_means,titles=testing_img_counts)
```

```
```

## Measurement¶

When we're evaluating our images to try and decide which number it represents, we need a way to score how well it matches the 10 mean examples we generated above.

There are two main conventions to do this:

- Take the mean of the absolute value of differences (absolute value is the function that replaces negative values with positive values). This is called the mean absolute difference or L1 norm
- Take the mean of the square of differences (which makes everything positive) and then take the square root (which undoes the squaring). This is called the root mean squared error (RMSE) or L2 norm.

For this project I started using the first, but then when i tried using the second i saw dramatically better results. Let's see if we can identify what's going on.

```
#def mnist_distance_L1_norm(a,b): return (a-b).abs().mean((-1,-2))
def mnist_distance_L1_norm(a,b): return F.l1_loss(a,b)
#F.l1_loss(a_3.float(),mean7), F.mse_loss(a_3,mean7).sqrt()
```

```
#def mnist_distance_L2_norm(a,b): return ((a - b)**2).mean().sqrt()
def mnist_distance_L2_norm(a,b): return F.mse_loss(a,b).sqrt()
```

Lets choose a digit and then use the above to see which number it's closer to

```
this_num = all_digits[2][0][3][23]
show_image(this_num)
```

Let's use our distance function to check each of the means and then make a prediction based on the smallest error

```
def predict(x,l2_norm = False):
if l2_norm:
tens = tensor([mnist_distance_L2_norm(x,n) for n in (all_means)])
else:
tens = tensor([mnist_distance_L1_norm(x,n) for n in (all_means)])
min_ten = torch.min(tens,-1)
idx = min_ten.indices.item()
return [idx, tens]
```

This function will output it's prediction, and then a tensor of all of the error scores for each of the numbers. The digit with the lowest error score will be the prediction. If the number was exactly the same as one of the means, it would score a zero. Below we can see it running first using L1 Norm, and then L2 Norm. Notice how the L2 norm results have a much higher spread between different digits.

```
predict(this_num,False)
```

```
predict(this_num,True)
```

This gets the answer here correct both times, so how about we try this on the testing sets to see how acurate things are in bulk. To do this we'll need a new function

```
def is_num(x,y,l2_norm = False):
return int(predict(x,l2_norm)[0]==y)
```

```
print('is this a 4?: ',is_num(this_num,4),' is this a 2?: ',is_num(this_num,2))
```

## Calculating our system's accuracy¶

```
def Average(lst):
return sum(lst) / len(lst)
def test_all(num,batch,l2_norm = False):
res = [is_num(x,num,l2_norm) for x in batch]
avg = Average(res )
return [num,avg,res,batch]
```

```
all_results = [test_all( i[1][0],i[1][3],False) for i in all_digits]
overal_accuracy = Average([i[1] for i in all_results])
overal_accuracy
```

This means that our similarity model gets the number right 66% of the time. This is much lower than the 90% that Jeremy got for his 3s and 7s detector, but makes sense given the added complexity of the greater number of potential numbers.

So let's dig in a bit and see where we're doing well and where we could do better.

```
df = pd.DataFrame([[i[0],i[1]] for i in all_results],columns=['number','accuracy']).set_index('number')
df.plot(kind='bar')
```

## Problem 5s¶

5s are clearly a problem. So lets take a look at some examples which are getting mis identified.

```
all_fives = all_results[5]
correct_fives = []
wrong_fives = []
for i in range(len(all_fives[2])):
if all_fives[2][i] == 1:
correct_fives.append(all_fives[3][i])
else:
wrong_fives.append(all_fives[3][i])
```

Our correct fives - we can just look at the first 5 and then dig into the actual predictions to see how close they were.

```
show_images(correct_fives[:5])
```

```
[predict(i,False) for i in correct_fives[:5]]
```

And let's do the same from our wrongly identified 5s and also take a look at what the system predicted them as - each one was predicted as being a different digit - what could be going on here?

```
show_images(wrong_fives[:5])
```

```
[predict(i,False) for i in wrong_fives[:5]]
```

Lets look at one of our wrong 5s and lets visualize what's correct and whats wrong.

```
this_five = wrong_fives[3]
show_image(this_five)
```

## Identifying differences¶

This 5 was incorrectly identified as a 1. Let's plot the differences between this character and the means for 5 and 1 to see if we can see what's causing this.

```
mean_five = all_digits[5][0][1]
mean_one = all_digits[1][0][1]
diff5 = abs(mean_five - this_five )
diff1 = abs(mean_one - this_five )
sum5 = int(diff5.sum().item())
sum1 = int(diff1.sum().item())
show_images([diff5,diff1],titles=[f'L1 norm from 5: {sum5}',f'L1 norm from 1: {sum1}'])
```

The darker areas show where the characers don't line up.
We can see that because this 5 is quite narrow, it leaves a lot of lightly shaded parts as a lot of the images of the mean 5 are wider.

When compared to the 1, there are much darker overlaps where the 5 extends outside the mean area, but there are a smaller number of light grey areas. When we total the sum of the differences, the 1 has a lower error score and thus this particular 5 is predicted to be a 1.
We can see here that in this case, the areas where the 5 extends outside the 1 mean are much more meaningfull than where the 5 doesn't cover all of the grey area for the 5.
Let's see how using RMSE or L2 Norm changes this.

```
diff5 = (mean_five - this_five )**2
diff1 = (mean_one - this_five )**2
sum5 = int(math.sqrt(diff5.sum().item()))
sum1 = int(math.sqrt(diff1.sum().item()))
show_images([diff5,diff1],titles=[f'L2 norm from 5: {sum5}',f'L2 norm from 1: {sum1}'])
```

This makes a big difference, with the larger the changes from the mean being weighted much higher and thus, in this case the 5 character would be sellected vs the 1. But how much of a change will this make to the system results in general.

```
all_results_l2 = [test_all( i[1][0],i[1][3],True) for i in all_digits]
overal_accuracy_l2 = Average([i[1] for i in all_results_l2])
overal_accuracy_l2
```

```
df = pd.DataFrame([[i[0],i[1]] for i in all_results_l2],columns=['number','accuracy']).set_index('number')
df.plot(kind='bar')
```

In this situation using RMSE has improved our system from 66% to 82%

```
```