<jupyter_start><jupyter_text>SuperResolution GANWe will be using imagenet (transfer learning for super resolution GAN creation)<jupyter_code>import fastai
from fastai.vision import *
from fastai.callbacks import *

from torchvision.models import vgg16_bn

import warnings
warnings.filterwarnings('ignore')<jupyter_output><empty_output><jupyter_text>Data<jupyter_code>path = untar_data(URLs.PETS)
path_hr = path/'images'
path_lr = path/'small-96'
path_mr = path/'small-256'
il = ImageImageList.from_folder(path_hr)
# shrink size of the images
def resize_one(fn,i, size, path):
    dest = path/fn.relative_to(path_hr)
    dest.parent.mkdir(parents=True, exist_ok=True)
    img = PIL.Image.open(fn)
    targ_sz = resize_to(img, size, use_min=True)
    img = img.resize(targ_sz, resample=PIL.Image.BILINEAR).convert('RGB')
    img.save(dest, quality=60)
# parallel is a function in fastai for parallel execution of the function
parallel(resize_one, il.items, 96, path_lr)
# create 256 size medium quality images and save them to path_mr folder
parallel(resize_one, il.items, 256, path_mr)
path.ls()
bs,size=32,128
arch = models.resnet34

src = ImageImageList.from_folder(path_lr).split_by_rand_pct(0.1, seed=42)
def get_data(bs,size):
    data = (src.label_from_func(lambda x: path_hr/x.name)
           .transform(get_transforms(max_zoom=2.), size=size, tfm_y=True)
           .databunch(bs=bs).normalize(imagenet_stats, do_y=True))
    return data
data = get_data(bs,size)
data
data.show_batch(ds_type=DatasetType.Valid, rows=2, figsize=(9,9))<jupyter_output><empty_output><jupyter_text>Feature lossFor SuperResolution GAN creation we use two types of losses* Base Loss (L1 loss/ MSE)* Feature Loss Feature loss is proposed in the paper [Perceptual Losses for Real-Time Style Transferand Super-Resolution](https://cs.stanford.edu/people/jcjohns/papers/eccv16/JohnsonECCV16.pdf)<jupyter_code>t = data.valid_ds[0][1].data
t = torch.stack([t,t])
def gram_matrix(x):
    n,c,h,w = x.size()
    x = x.view(n, c, -1)
    return (x @ x.transpose(1,2))/(c*h*w)
gram_matrix(t)
# L1 loss is base loss
base_loss = F.l1_loss
# loading vgg16 model to GPU
vgg_m = vgg16_bn(True).features.cuda().eval()
requires_grad(vgg_m, False)
# Identifying the layers where MaxPooling is being done
blocks = [i-1 for i,o in enumerate(children(vgg_m)) if isinstance(o,nn.MaxPool2d)]
blocks, [vgg_m[i] for i in blocks]<jupyter_output><empty_output><jupyter_text>![Feature Loss](https://miro.medium.com/max/1710/1*TdkNFoecrvBZZbLOHGse0Q.png)<jupyter_code>class FeatureLoss(nn.Module):
    def __init__(self, m_feat, layer_ids, layer_wgts):
        super().__init__()
        self.m_feat = m_feat
        self.loss_features = [self.m_feat[i] for i in layer_ids]
        self.hooks = hook_outputs(self.loss_features, detach=False)
        self.wgts = layer_wgts
        self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))] + [f'gram_{i}' for i in range(len(layer_ids))]

    def make_features(self, x, clone=False):
        self.m_feat(x)
        return [(o.clone() if clone else o) for o in self.hooks.stored]
    
    def forward(self, input, target):
        out_feat = self.make_features(target, clone=True)
        in_feat = self.make_features(input)
        self.feat_losses = [base_loss(input,target)]
        self.feat_losses += [base_loss(f_in, f_out)*w
                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
        self.feat_losses += [base_loss(gram_matrix(f_in), gram_matrix(f_out))*w**2 * 5e3
                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
        self.metrics = dict(zip(self.metric_names, self.feat_losses))
        return sum(self.feat_losses)
    
    def __del__(self): self.hooks.remove()
feat_loss = FeatureLoss(vgg_m, blocks[2:5], [5,15,2]) # featured model = vgg_m, layer_ids = sending last three layers in blocks<jupyter_output><empty_output><jupyter_text>Train<jupyter_code>wd = 1e-3
learn = unet_learner(data, arch, wd=wd, loss_func=feat_loss, callback_fns=LossMetrics, blur=True, norm_type=NormType.Weight)
gc.collect();
learn.lr_find()
learn.recorder.plot()
lr = 1e-3
# function to fit, save and show_results
def do_fit(save_name, lrs=slice(lr), pct_start=0.9):
    learn.fit_one_cycle(5, lrs, pct_start=pct_start)
    learn.save(save_name)
    learn.show_results(rows=1, imgsize=5)
do_fit('1a', slice(lr*10))
learn.unfreeze()
do_fit('1b', slice(1e-5,lr))
# increase size and half the batch size for the GPU to store data
data = get_data(12,size*2)
learn.data = data
learn.freeze()
gc.collect();
learn.load('1b');
do_fit('2a')
learn.unfreeze()
do_fit('2b', slice(1e-6,1e-4), pct_start=0.3)<jupyter_output><empty_output><jupyter_text>Test<jupyter_code># set not using object to None and object wll be removed from memory
learn = None
gc.collect();
learn = unet_learner(data, arch, loss_func=F.l1_loss, blur=True, norm_type=NormType.Weight)
data_mr = (ImageImageList.from_folder(path_mr).split_by_rand_pct(0.1, seed=42)
          .label_from_func(lambda x: path_hr/x.name)
          .transform(get_transforms(), size=(1280,1600), tfm_y=True)
          .databunch(bs=1).normalize(imagenet_stats, do_y=True))
data_mr.c = 3
learn.load('2b');
learn.data = data_mr
fn = data_mr.valid_ds.x.items[0]; fn
img = open_image(fn); img.shape
p,img_hr,b = learn.predict(img)
show_image(img, figsize=(18,15), interpolation='nearest');
Image(img_hr).show(figsize=(18,15))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1335891812865497, 'fraction_numerical': 0.02138157894736842, 'mean_word_length': 4.853475935828877, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '382406', 'license': 'MIT', 'n_tokens_mistral': 2135, 'n_tokens_neox': 2064, 'n_words': 416, 'path': 'fast.Ai/dl1/FastAi7_superres-gan.ipynb', 'repo_name': 'harish678/Machine-Learning', 'size': '5472'}