{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage import io, transform\nimport os\nimport xml.etree.ElementTree  as ET\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm, tqdm_notebook\nimport gc\nfrom keras.layers import Lambda, Input, Dropout, Dense, Embedding, Flatten, Activation, BatchNormalization, Reshape, UpSampling2D\nfrom keras.optimizers import Adam\nfrom keras.layers.convolutional import Conv2D, Conv2DTranspose\nfrom keras.models import Model\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.initializers import RandomNormal\nfrom keras import backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_images(padding=True):\n    base_dir = \"../input/annotation/Annotation/\"\n    img_dir = \"../input/all-dogs/all-dogs/\"\n    paths = []\n    imgs = []\n    ret = os.listdir(base_dir)\n    for x in ret:\n        for y in os.listdir(base_dir + x):\n            paths.append(base_dir + x + \"/\" + y)\n\n    for x in tqdm_notebook(paths):\n        try:\n            tree = ET.ElementTree()\n            root = tree.parse(x)\n            img_path = img_dir + root.find(\"filename\").text + \".jpg\"\n            x1 = int(root.find(\"object\").find(\"bndbox\").find(\"xmin\").text)\n            y1 = int(root.find(\"object\").find(\"bndbox\").find(\"ymin\").text)\n            x2 = int(root.find(\"object\").find(\"bndbox\").find(\"xmax\").text)\n            y2 = int(root.find(\"object\").find(\"bndbox\").find(\"ymax\").text)\n            img = io.imread(img_path)\n            img = img[y1:y2 + 1, x1:x2 + 1, :]\n            \n            if padding:\n                width = x2 - x1 + 1\n                height = y2 - y1 + 1\n                if height > width:\n                    width = int(64.0 * width / height)\n                    height = 64\n                    img = transform.resize(img, output_shape=(height, width, 3), preserve_range=True) / 255.0\n                    img = np.pad(img, ((0, 0), ((64 - width) // 2, (64 - width) - (64 - width) // 2), (0, 0)), \n                           mode=\"constant\", constant_values=0.0)\n                else:\n                    height = int(64.0 * height / width)\n                    width = 64\n                    img = transform.resize(img, output_shape=(height, width, 3), preserve_range=True) / 255.0\n                    img = np.pad(img, (((64 - height) // 2, (64 - height) - (64 - height) // 2), (0, 0), (0, 0)), \n                           mode=\"constant\", constant_values=0.0)\n            else:\n                img = transform.resize(img, output_shape=(64, 64, 3), preserve_range=True) / 255.0\n            imgs.append(img[np.newaxis, :, :, :])\n        except:\n            pass\n    \n    del paths\n    \n    return imgs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = get_images(padding=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generator():\n    init = RandomNormal(stddev=0.02)\n    z = Input(shape=(256,), name=\"noise\")\n    x = Reshape(target_shape=(1, 1, 256))(z)\n    x = Activation(\"relu\")(\n        BatchNormalization(momentum=0.1)(\n            Conv2DTranspose(1024, 4, kernel_initializer=init, use_bias=False)(x)\n        )\n    )\n    x = Activation(\"relu\")(\n        BatchNormalization(momentum=0.1)(\n            Conv2DTranspose(512, 4, strides=(2, 2), padding=\"same\",\n                            kernel_initializer=init, use_bias=False)(x)\n        )\n    )\n    x = Activation(\"relu\")(\n        BatchNormalization(momentum=0.1)(\n            Conv2DTranspose(256, 4, strides=(2, 2), padding=\"same\",\n                            kernel_initializer=init, use_bias=False)(x)\n        )\n    )\n    x = Activation(\"relu\")(\n        BatchNormalization(momentum=0.1)(\n            Conv2DTranspose(128, 4, strides=(2, 2), padding=\"same\",\n                            kernel_initializer=init, use_bias=False)(x)\n        )\n    )\n    x = Activation(\"relu\")(\n        BatchNormalization(momentum=0.1)(\n            Conv2DTranspose(64, 4, strides=(2, 2), padding=\"same\",\n                            kernel_initializer=init, use_bias=False)(x)\n        )\n    )\n    x = Activation(\"tanh\")(\n        Conv2DTranspose(3, 3, padding=\"same\", kernel_initializer=init)(x)\n    )\n    model = Model(z, x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def discrimator():\n    init = RandomNormal(stddev=0.02)\n    img = Input(shape=(64, 64, 3), name=\"image\")\n    x = LeakyReLU(0.2)(Conv2D(32, 4, strides=(2, 2), \n                              padding=\"same\", kernel_initializer=init)(img))\n    x = LeakyReLU(0.2)(Conv2D(64, 4, strides=(2, 2), \n                              padding=\"same\", kernel_initializer=init)(x))\n    x = LeakyReLU(0.2)(\n        BatchNormalization(momentum=0.1)(\n             Conv2D(128, 4, strides=(2, 2), \n                    padding=\"same\", kernel_initializer=init,\n                    use_bias=False)(x)\n        )\n       )\n    x = LeakyReLU(0.2)(\n        BatchNormalization(momentum=0.1)(\n             Conv2D(256, 4, strides=(2, 2), \n                    padding=\"same\", kernel_initializer=init,\n                    use_bias=False)(x)\n        )\n    )\n    x = Conv2D(1, 4, kernel_initializer=init, use_bias=False)(x)\n    x = Flatten()(x)\n    model = Model(img, x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def descrimator_combine(g, d):\n    g.trainable = False\n    d.trainable = True\n    \n    z = Input(shape=(256,), name=\"noise\")\n    img = Input(shape=(64, 64, 3), name=\"image\")\n    x1 = d(img)\n    x2 = d(g(z))\n    \n    out1 = Lambda(lambda x: x[0] - K.mean(x[1]))([x1, x2])\n    out2 = Lambda(lambda x: K.mean(x[0]) - x[1])([x1, x2])\n    model = Model([z, img], [out1, out2])\n    return model\n    \n\ndef generator_combine(g, d):\n    g.trainable = True\n    d.trainable = False\n    \n    z = Input(shape=(256,), name=\"noise\")\n    img = Input(shape=(64, 64, 3), name=\"image\")\n    x1 = d(img)\n    x2 = d(g(z))\n    \n    out1 = Lambda(lambda x: x[1] - K.mean(x[0]))([x1, x2])\n    out2 = Lambda(lambda x: K.mean(x[1]) - x[0])([x1, x2])\n    model = Model([z, img], [out1, out2])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def scale_cos(start, end, x):\n    return start + (1 + np.cos(np.pi * (1 - x))) * (end - start) / 2\n\n\t\ndef rate_decay(x):\n\tif x < 0.2:\n\t\treturn scale_cos(0.00001, 0.0004, x / 0.2)\n\telse:\n\t\treturn scale_cos(0.0004, 0.00001, (x - 0.2)/ 0.8) \n    \nx = list(map(lambda x: x / 10000.0, list(range(0, 10000))))\nplt.plot(x, list(map(rate_decay, x)))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def train(imgs, epochs, batch_size=4):\n    d = discrimator()\n    g = generator()\n    d_model = descrimator_combine(g, d)\n    d_model.compile(loss=\"mse\", optimizer=Adam(0.0001, 0.5),\n                   loss_weights=[0.5, 0.5])\n    g_model = generator_combine(g, d)\n    g_model.compile(loss=\"mse\", optimizer=Adam(0.0001, 0.5),\n                   loss_weights=[0.5, 0.5])\n    d_model.summary()\n    g_model.summary()\n    \n    true_label = np.ones(shape=(batch_size, 1))\n    \n    datagen = ImageDataGenerator(\n        rotation_range=5,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n\n    idx = 0\n    for _ in range(epochs):\n        gc.collect()\n        index = len(imgs) // batch_size\n        count = 0\n        for img_in in datagen.flow(x=np.vstack(imgs), batch_size=batch_size, shuffle=True):\n            count += 1\n            if count == index:\n                break\n            smooth = np.random.uniform(0, 0.1)\n            img_in = (img_in - 0.5) * 2\n            noise = np.random.randn(batch_size, 256)\n          \n            d_loss = d_model.train_on_batch(x=[noise, img_in],\n                                         y=[true_label * (1 - smooth), true_label * (1 - smooth)])\n            \n            for _ in range(1):\n                g_loss = g_model.train_on_batch(x=[noise, img_in], \n                                             y=[true_label * (1 - smooth), true_label * (1 - smooth)])\n            \n            if idx % 100 == 0:\n                print(\"idx:\", idx, \"d_loss:\", d_loss, \"g_loss:\", g_loss)\n            idx += 1\n            \n            K.set_value(d_model.optimizer.lr, rate_decay(idx * 1.0 / (index * epochs)))\n            K.set_value(g_model.optimizer.lr, rate_decay(idx * 1.0 / (index * epochs)))\n                \n    return d, g","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.shuffle(imgs)\nd, g = train(imgs=imgs, epochs=300, batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from scipy.stats import truncnorm\n\ndef truncated_normal(size, threshold=1):\n    values = truncnorm.rvs(-threshold, threshold, size=size)\n    return values\n\nnoise = truncated_normal((10000, 256), 3)\ngen_imgs = g.predict(noise)\ngen_imgs = (gen_imgs + 1) / 2\ngen_imgs = (gen_imgs * 255).astype(np.uint8)\nif not os.path.exists(\"result\"):\n    os.makedirs(\"result\")\nfor i in range(10000):\n    io.imsave(\"result/\" + str(i) + \".png\", gen_imgs[i])\nimport shutil\nshutil.make_archive('images', 'zip', 'result')\nshutil.rmtree('result')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"code","source":"","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}