<jupyter_start><jupyter_text>Pretrained GAN<jupyter_code>import fastai
from fastai import *
from fastai.vision import *
from fastai.callbacks import *

from torchvision.models import vgg16_bn
path = untar_data(URLs.PETS)
path_hr = path/'images'
path_lr = path/'crappy'<jupyter_output><empty_output><jupyter_text>Critic data Prepare the input data by crappifying images.<jupyter_code>def crappify(fn,i):
    dest = path_lr/fn.relative_to(path_hr)
    dest.parent.mkdir(parents=True, exist_ok=True)
    img = PIL.Image.open(fn)
    targ_sz = resize_to(img, 96, use_min=True)
    img = img.resize(targ_sz, resample=PIL.Image.BILINEAR).convert('RGB')
    img.save(dest, quality=random.randint(10,70))<jupyter_output><empty_output><jupyter_text>Uncomment the first time you run this notebook.<jupyter_code>#il = ImageItemList.from_folder(path_hr)
#parallel(crappify, il.items)<jupyter_output><empty_output><jupyter_text>For gradual resizing we can change the commented line here.<jupyter_code>bs,size = 32,128
# bs,size = 8,256
arch = models.resnet34
classes = ['crappy', 'images']
src = ImageItemList.from_folder(path, include=classes).random_split_by_pct(0.1, seed=42)
ll = src.label_from_folder(classes=classes)
data_crit = (ll.transform(get_transforms(max_zoom=2.), size=size)
       .databunch(bs=bs).normalize(imagenet_stats))

data_crit.c = 3
data_crit.show_batch(rows=4, ds_type=DatasetType.Valid)<jupyter_output><empty_output><jupyter_text>Train critic<jupyter_code>conv_args = dict(leaky=0.2, norm_type=NormType.Spectral)

def conv(ni:int, nf:int, ks:int=3, stride:int=1, **kwargs):
    return conv_layer(ni, nf, ks=ks, stride=stride, **conv_args, **kwargs)

def critic(n_channels:int=3, nf:int=128, n_blocks:int=3, p:int=0.25):
    layers = [
        conv(n_channels, nf, ks=4, stride=2),
        nn.Dropout2d(p/2),
        # Removed conv_args since spectral norm makes training slow here
        res_block(nf, dense=True)] # , **conv_args)]
    nf *= 2 # after dense block
    for i in range(n_blocks):
        layers += [
            nn.Dropout2d(p),
            conv(nf, nf*2, ks=4, stride=2, self_attention=(i==0))]
        nf *= 2
    layers += [
        conv(nf, 1, ks=4, bias=False, padding=0, use_activ=False),
        Flatten()]
    return nn.Sequential(*layers)<jupyter_output><empty_output><jupyter_text>Module to apply the loss function to every element of the last features before taking the mean.<jupyter_code>class AdaptiveLoss(nn.Module):
    def __init__(self, crit):
        super().__init__()
        self.crit = crit

    def forward(self, output, target):
        return self.crit(output, target[:,None].expand_as(output).float())<jupyter_output><empty_output><jupyter_text>Specific accuracy metric.<jupyter_code>def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
    "Compute accuracy when `y_pred` and `y_true` are the same size."
    if sigmoid: y_pred = y_pred.sigmoid()
    return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).byte()).float().mean()<jupyter_output><empty_output><jupyter_text>Pretrain the critic on crappy vs not crappy.<jupyter_code>learn_critic = Learner(data_crit, critic(), metrics=accuracy_thresh_expand, loss_func=AdaptiveLoss(nn.BCEWithLogitsLoss()))
learn_critic.fit_one_cycle(6, 1e-3)
learn_critic.fit_one_cycle(6, 1e-3)
learn_critic.save('critic-pre')<jupyter_output><empty_output><jupyter_text>Pre-train generator Now let's pretrain the generator.<jupyter_code>arch = models.resnet34
src = ImageImageList.from_folder(path_lr).random_split_by_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))

    data.c = 3
    return data
data_gen = get_data(bs,size)
wd = 1e-3
learn_gen = unet_learner(data_gen, arch, wd=wd, blur=True, norm_type=NormType.Spectral, self_attention=True, sigmoid=True,
                         loss_func=MSELossFlat())
learn_gen.fit_one_cycle(2, pct_start=0.8)
learn_gen.unfreeze()
learn_gen.fit_one_cycle(2, slice(1e-6,1e-3))
learn_gen.show_results(rows=8)
learn_gen.save('gen-pre')<jupyter_output><empty_output><jupyter_text>GAN Now we'll combine those pretrained model in a GAN.<jupyter_code>from fastai.vision.gan import *<jupyter_output><empty_output><jupyter_text>Those are the losses from before.<jupyter_code>loss_critic = AdaptiveLoss(nn.BCEWithLogitsLoss())
loss_gen    = MSELossFlat()
learn_crit = Learner(data_crit, critic(), loss_func=loss_critic).load('critic-pre')
learn_gen = unet_learner(data_gen, arch, wd=wd, blur=True, norm_type=NormType.Spectral,
                         self_attention=True, loss_func=loss_gen).load('gen-pre')<jupyter_output><empty_output><jupyter_text>To define a GAN Learner, we just have to specify the learner objects foor the generator and the critic. The switcher is a callback that decides when to switch from discriminator to generator and vice versa. Here we do as many iterations of the discriminator as needed to get its loss back < 0.5 then one iteration of the generator.The loss of the critic is given by `learn_crit.loss_func`. We take the average of this loss function on the batch of real predictions (target 1) and the batch of fake predicitions (target 0). The loss of the generator is weighted sum (weights in `weights_gen`) of `learn_crit.loss_func` on the batch of fake (passed throught the critic to become predictions) with a target of 1, and the `learn_gen.loss_func` applied to the output (batch of fake) and the target (corresponding batch of superres images).<jupyter_code>switcher = partial(AdaptiveGANSwitcher, critic_thresh=0.5)
learn = GANLearner.from_learners(learn_gen, learn_crit, weights_gen=(1.,50.), show_img=False, switcher=switcher,
                                 opt_func=optim.RMSprop, wd=0)
learn.fit_one_cycle(60,1e-4, pct_start=0, moms=(0.9))
#Adaptive schedule 0.5, 60 epochs, lr=1e-4 from size 256
learn.fit(60,1e-4)<jupyter_output><empty_output><jupyter_text>Finetuning at a lower learning rate.<jupyter_code>learn.fit(20,1e-5)
#Adaptive schedule 0.5, 60 epochs, lr=1e-4 + fine-tuned 20 epochs 1e-5
learn.show_results()
#Adaptive schedule 0.5, 60 epochs, lr=1e-4
learn.show_results()
#Fixed schedule 1 to 5, 60 epochs, lr=1e-4
learn.show_results()
learn.save('size256f')
torch.save(learn.gan_trainer.opt_critic.state_dict(), path/'models'/'opt_crit_256f.pth')
torch.save(learn.gan_trainer.opt_gen.state_dict(), path/'models'/'opt_gen_256f.pth')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12184746277727135, 'fraction_numerical': 0.02218170768763294, 'mean_word_length': 5.51137487636004, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '122434', 'license': 'Apache-2.0', 'n_tokens_mistral': 2480, 'n_tokens_neox': 2374, 'n_words': 496, 'path': 'deep-learning/fastai-docs/fastai_docs-master/dev_nb/discriminator.ipynb', 'repo_name': 'AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials', 'size': '6582'}