{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport xml.etree.ElementTree as ET\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport os\nfrom tqdm import tqdm_notebook as tqdm\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nimport os\nfrom tqdm import tqdm_notebook as tqdm\nfrom sklearn.cluster import KMeans","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# GAN Network\nhttps://www.kaggle.com/wendykan/gan-dogs-starter"},{"metadata":{"trusted":true},"cell_type":"code","source":"class Generator(nn.Module):\n    def __init__(self, nz, nfeats, nchannels):\n        super(Generator, self).__init__()\n\n        # input is Z, going into a convolution\n        self.conv1 = nn.ConvTranspose2d(nz, nfeats * 8, 4, 1, 0, bias=False)\n        self.bn1 = nn.BatchNorm2d(nfeats * 8)\n        # state size. (nfeats*8) x 4 x 4\n        \n        self.conv2 = nn.ConvTranspose2d(nfeats * 8, nfeats * 8, 4, 2, 1, bias=False)\n        self.bn2 = nn.BatchNorm2d(nfeats * 8)\n        # state size. (nfeats*8) x 8 x 8\n        \n        self.conv3 = nn.ConvTranspose2d(nfeats * 8, nfeats * 4, 4, 2, 1, bias=False)\n        self.bn3 = nn.BatchNorm2d(nfeats * 4)\n        # state size. (nfeats*4) x 16 x 16\n        \n        self.conv4 = nn.ConvTranspose2d(nfeats * 4, nfeats * 2, 4, 2, 1, bias=False)\n        self.bn4 = nn.BatchNorm2d(nfeats * 2)\n        # state size. (nfeats * 2) x 32 x 32\n        \n        self.conv5 = nn.ConvTranspose2d(nfeats * 2, nfeats, 4, 2, 1, bias=False)\n        self.bn5 = nn.BatchNorm2d(nfeats)\n        # state size. (nfeats) x 64 x 64\n        \n        self.conv6 = nn.ConvTranspose2d(nfeats, nchannels, 3, 1, 1, bias=False)\n        # state size. (nchannels) x 64 x 64\n\n    def forward(self, x):\n        x = F.leaky_relu(self.bn1(self.conv1(x)))\n        x = F.leaky_relu(self.bn2(self.conv2(x)))\n        x = F.leaky_relu(self.bn3(self.conv3(x)))\n        x = F.leaky_relu(self.bn4(self.conv4(x)))\n        x = F.leaky_relu(self.bn5(self.conv5(x)))\n        x = torch.tanh(self.conv6(x))\n        return x\n\n\n\nclass Discriminator(nn.Module):\n    def __init__(self, nchannels, nfeats):\n        super(Discriminator, self).__init__()\n\n        # input is (nchannels) x 64 x 64\n        self.conv1 = nn.Conv2d(nchannels, nfeats, 4, 2, 1, bias=False)\n        # state size. (nfeats) x 32 x 32\n        \n        self.conv2 = nn.Conv2d(nfeats, nfeats * 2, 4, 2, 1, bias=False)\n        self.bn2 = nn.BatchNorm2d(nfeats * 2)\n        # state size. (nfeats*2) x 16 x 16\n        \n        self.conv3 = nn.Conv2d(nfeats * 2, nfeats * 4, 4, 2, 1, bias=False)\n        self.bn3 = nn.BatchNorm2d(nfeats * 4)\n        # state size. (nfeats*4) x 8 x 8\n       \n        self.conv4 = nn.Conv2d(nfeats * 4, nfeats * 8, 4, 2, 1, bias=False)\n        self.bn4 = nn.BatchNorm2d(nfeats * 8)\n        # state size. (nfeats*8) x 4 x 4\n        \n        self.conv5 = nn.Conv2d(nfeats * 8, 1, 4, 1, 0, bias=False)\n        # state size. 1 x 1 x 1\n        \n    def forward(self, x):\n        x = F.leaky_relu(self.conv1(x), 0.2)\n        x = F.leaky_relu(self.bn2(self.conv2(x)), 0.2)\n        x = F.leaky_relu(self.bn3(self.conv3(x)), 0.2)\n        x = F.leaky_relu(self.bn4(self.conv4(x)), 0.2)\n        x = torch.sigmoid(self.conv5(x))\n        \n        return x.view(-1, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imagesPath = os.listdir('../input/all-dogs/all-dogs/')\nbreedsPath = os.listdir('../input/annotation/Annotation/')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# make trainData (dog only)\nhttps://www.kaggle.com/paulorzp/show-annotations-and-breeds"},{"metadata":{"trusted":true},"cell_type":"code","source":"trainData = []\nidxIn = 0\nfor breed in tqdm(breedsPath):\n    for dog in os.listdir('../input/annotation/Annotation/'+breed):\n        try:\n            img = Image.open('../input/all-dogs/all-dogs/'+dog+'.jpg') \n        except:\n            continue           \n        tree = ET.parse('../input/annotation/Annotation/'+breed+'/'+dog)\n        root = tree.getroot()\n        objects = root.findall('object')\n        for o in objects:\n            bndbox = o.find('bndbox') \n            xmin = int(bndbox.find('xmin').text)\n            ymin = int(bndbox.find('ymin').text)\n            xmax = int(bndbox.find('xmax').text)\n            ymax = int(bndbox.find('ymax').text)\n            img2 = img.crop((xmin, ymin, xmax, ymax))\n            img2 = img2.resize((64,64), Image.ANTIALIAS)\n            trainData.append(np.asarray(img2))\ntrainData = np.array(trainData)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# plot Train Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"for k in range(5):\n    plt.figure(figsize=(15, 3))\n    for j in range(5):\n        x = np.random.choice(len(trainData))\n        plt.subplot(1, 5, j + 1)\n        img = Image.fromarray( (trainData[x]).astype('uint8').reshape((64,64,3)))\n        plt.axis('off')\n        plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"trainData = trainData.transpose(0, 3, 1, 2)\ntrainData = trainData / 122.5 - 1\ntrainData = torch.tensor(trainData).float()\nbatch_size = 32\ntrain_loader = torch.utils.data.DataLoader(trainData, shuffle=True,\n                                           batch_size=batch_size)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nlr = 0.0005\nbeta1 = 0.5\n\nnetG = Generator(100, 32, 3).to(device)\nnetD = Discriminator(3, 48).to(device)\n\ncriterion = nn.BCELoss()\n\noptimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))\n\nnz = 100\nfixed_noise = torch.randn(25, nz, 1, 1, device=device)\n\nreal_label = 0.9\nfake_label = 0\nbatch_size = train_loader.batch_size\n\n\n\n### training here\n\nepochs = 25\n\nstep = 0\nfor epoch in range(epochs):\n    for ii, real_images in enumerate(train_loader):\n        ############################\n        # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n        ###########################\n        # train with real\n        netD.zero_grad()\n        real_images = real_images.to(device)\n        batch_size = real_images.size(0)\n        labels = torch.full((batch_size, 1), real_label, device=device)\n        output = netD(real_images)\n        errD_real = criterion(output, labels)\n        errD_real.backward()\n        D_x = output.mean().item()\n\n        # train with fake\n        noise = torch.randn(batch_size, nz, 1, 1, device=device)\n        fake = netG(noise)\n        labels.fill_(fake_label)\n        output = netD(fake.detach())\n        errD_fake = criterion(output, labels)\n        errD_fake.backward()\n        D_G_z1 = output.mean().item()\n        errD = errD_real + errD_fake\n        optimizerD.step()\n\n        ############################\n        # (2) Update G network: maximize log(D(G(z)))\n        ###########################\n        netG.zero_grad()\n        labels.fill_(real_label)  # fake labels are real for generator cost\n        output = netD(fake)\n        errG = criterion(output, labels)\n        errG.backward()\n        D_G_z2 = output.mean().item()\n        optimizerG.step()\n        \n        if step % 500 == 0:\n            print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f / %.4f'\n                  % (epoch + 1, epochs, ii, len(train_loader),\n                     errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n            \n            valid_image = netG(fixed_noise)\n        step += 1\n     ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Output Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"im_batch_size = 50\nn_images = 30000\nout_images_cand = np.zeros([n_images, 3, 64, 64])\nfor i_batch in tqdm(range(0, n_images, im_batch_size)):\n    gen_z = torch.randn(im_batch_size, 100, 1, 1, device=device)\n    gen_images = netG(gen_z)\n    images = gen_images.to(\"cpu\").clone().detach()\n    out_images_cand[i_batch : i_batch + im_batch_size, :, :, :] = images.numpy()\nout_images_cand = torch.tensor(out_images_cand).float()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = np.zeros([n_images])\nfor i_batch in tqdm(range(0, n_images, im_batch_size)):\n    scores[i_batch: i_batch + im_batch_size] = netD(out_images_cand[i_batch : i_batch + im_batch_size]).to(\"cpu\").clone().detach().numpy().reshape([-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = KMeans(n_clusters=10000, n_init=1, max_iter=50, tol=0.01).fit_predict(scores.reshape([-1, 1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"out_images = np.zeros([10000, 3, 64, 64])\nfor i in tqdm(range(10000)):\n    out_images[i, :, :, :] = out_images_cand[np.where(pred==i)[0][0], :, :, :]\nout_images = out_images.transpose(0, 2, 3, 1)\nout_images = ((out_images + 1) * 122.5).astype(int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 0\nfor k in range(5):\n    plt.figure(figsize=(15,3))\n    for j in range(5):\n        plt.subplot(1,5,j+1)\n        img = Image.fromarray( (out_images[idx]).astype('uint8').reshape((64,64,3)))\n        plt.axis('off')\n        plt.imshow(img)\n        idx += 1\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not os.path.exists('../output_images'):\n    os.mkdir('../output_images')\nfor i in tqdm(range(0, 10000)):\n    pil_img = Image.fromarray(out_images[i, :, :, :].astype('uint8').reshape((64,64,3)))\n    pil_img.save(os.path.join('../output_images', f'image_{i:05d}.png'))\nimport shutil\nshutil.make_archive('images', 'zip', '../output_images')","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}