<jupyter_start><jupyter_text><jupyter_code>!pip3 install fastcore==1.0.9
!pip3 install fastai==1.0.42
!pip3 install -Uqq fastbook
from torchvision import transforms
import fastbook
fastbook.setup_book()

#hide
from fastbook import *
from fastai.vision.all import *
path = untar_data(URLs.MNIST_SAMPLE)
Path.BASE_PATH = path
(path/"valid"/"3").ls()
valid_3_tens = torch.stack([tensor(Image.open(o)) for o in (path/"valid"/"3").ls()])
valid_7_tens = torch.stack([tensor(Image.open(o)) for o in (path/"valid"/"7").ls()])
valid_3_tens = valid_3_tens.float()/255
valid_7_tens = valid_7_tens.float()/255
valid_3_tens.shape, valid_7_tens.shape
def mnist_distance(a, b) : return (a-b).abs().mean((-1, -2))
a_3 = tensor(Image.open((path/"valid"/"3").ls()[1]))
train_3_tens = torch.stack([tensor(Image.open(o)) for o in (path/"train"/"3").ls()])
train_7_tens = torch.stack([tensor(Image.open(o)) for o in (path/"train"/"7").ls()])
train_3_tens = train_3_tens.float()/255
train_7_tens = train_7_tens.float()/255
mean3 = train_3_tens.mean(0)
mean7 = train_7_tens.mean(0)
mnist_distance(a_3, mean3)
mean3.shape
mnist_distance(a_3, mean7)
from torchvision import transforms
trans = transforms.ToPILImage()
trans(a_3)
F.mse_loss(a_3, mean3).sqrt()
F.mse_loss(a_3, mean7).sqrt()
trans(mean7)
tensor([1, 1, 1]) + tensor([2, 3, 4])
def is_3(x) : return mnist_distance(x, mean3) < mnist_distance(x, mean7)
is_3(a_3)
is_3(mean7)
is_3(a_3).float()
valid_3_tens_is_3 = is_3(valid_3_tens).float().mean()
valid_7_tens_is_3 = is_3(valid_7_tens).float().mean()
valid_3_tens_is_3
valid_7_tens_is_3
 t = tensor(3.0).requires_grad_()
def f(x) : return x**2
y = f(t)
y.backward()
t
t.grad
y
t.grad
 print(t.grad)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17815420560747663, 'fraction_numerical': 0.054322429906542055, 'mean_word_length': 6.546255506607929, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 5, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '496607', 'license': 'MIT', 'n_tokens_mistral': 782, 'n_tokens_neox': 759, 'n_words': 128, 'path': 'lesson3.ipynb', 'repo_name': 'Sunil1821/FastAIPractise', 'size': '1712'}