{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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 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\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"def get_images():\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            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            img = (img - 0.5) * 2\n            imgs.append(img)\n        except:\n            pass\n    \n    del paths\n    return imgs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = get_images()\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generator():\n    init = RandomNormal(stddev=0.02)\n    z = Input(shape=(100,), name=\"noise\")\n    x = Dense(4 * 4 * 64, kernel_initializer=init)(z)\n    x = Reshape(target_shape=(4, 4, 64))(x)\n    x = Conv2D(128, 3, activation=\"relu\", kernel_initializer=init, padding=\"same\")(UpSampling2D()(x))\n    x = Conv2D(128, 3, activation=\"relu\", kernel_initializer=init, padding=\"same\")(UpSampling2D()(x))\n    x = Conv2D(128, 3, activation=\"relu\", kernel_initializer=init, padding=\"same\")(UpSampling2D()(x))\n    x = Conv2D(128, 3, activation=\"relu\", kernel_initializer=init, padding=\"same\")(UpSampling2D()(x))\n    x = Conv2D(3, 3, activation=\"tanh\", kernel_initializer=init, padding=\"same\")(x)\n    model = Model(z, x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = generator()\nmodel.summary()","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 = Dropout(0.25)(LeakyReLU(0.2)(Conv2D(128, 3, strides=(2, 2), \n                                            padding=\"same\", kernel_initializer=init)(img)))\n    x = Dropout(0.25)(LeakyReLU(0.2)(Conv2D(128, 3, strides=(2, 2), \n                                            padding=\"same\", kernel_initializer=init)(x)))\n    x = Dropout(0.25)(LeakyReLU(0.2)(Conv2D(128, 3, strides=(2, 2), \n                                            padding=\"same\", kernel_initializer=init)(x)))\n    x = Dropout(0.25)(LeakyReLU(0.2)(Conv2D(128, 3, strides=(2, 2), \n                                            padding=\"same\", kernel_initializer=init)(x)))\n    x = Flatten()(x)\n    x = Dense(1, kernel_initializer=init, activation=\"sigmoid\")(x)\n    model = Model(img, x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = discrimator()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def train(imgs, epochs, batch_size=4):\n    d = discrimator()\n    d.compile(loss='binary_crossentropy',\n              optimizer=Adam(0.0006, 0.5), \n              metrics=['accuracy'])\n    \n    d.trainable = False\n    g = generator()\n    z = Input(shape=(100,), name=\"noise\")\n    x = d(g(z))\n    combine = Model(z, x)\n    combine.compile(loss='binary_crossentropy',\n                    optimizer=Adam(0.0004, 0.5),\n                    metrics=['accuracy'])\n    \n    d.summary()\n    combine.summary()\n    \n    true_label = np.ones(shape=(batch_size, 1))\n    false_label = np.zeros(shape=(batch_size, 1))\n    \n    for _ in range(epochs):\n        index = len(imgs) // batch_size\n        for idx in range(index):\n            smooth = np.random.uniform(0, 0.1)\n            img_in = np.array(imgs[idx * batch_size : (idx + 1) * batch_size])\n            noise = np.random.randn(batch_size,100)\n            gen_imgs = g.predict(noise)\n          \n            # 训练D, 使D能分辨真假\n            d.trainable = True\n            real_loss = d.train_on_batch(x=img_in, y=true_label * (1 - smooth))\n            fake_loss = d.train_on_batch(x=gen_imgs, y=false_label)\n            d_loss = (real_loss[0] + fake_loss[0]) / 2\n            d_accu = (real_loss[1] + fake_loss[1]) / 2\n            \n            # 训练G, 使G往真的方向走, 因为noise是相同的, 所以和D训练的样本是一致的\n            d.trainable = False\n            g_loss = combine.train_on_batch(x=noise, y=true_label * (1 - smooth))\n            \n            if idx % 100 == 0:\n                print(\"idx:\", idx, \"d_loss:\", d_loss, \"g_loss:\", g_loss[0], \"d_accu:\", d_accu)\n                \n    return d, g","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = imgs[:10000]\nnp.random.shuffle(imgs)\nd, g = train(imgs=imgs, epochs=200, batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"noise = np.random.uniform(-1.0, 1.0, [10000, 100])\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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}