{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Dogs vs Cats"},{"metadata":{},"cell_type":"markdown","source":"https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition"},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.applications import vgg16\n\nprint(tf.__version__)\nprint(tf.executing_eagerly())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\n\nDataset = \"train\"\n\n\nwith zipfile.ZipFile(\"../input/dogs-vs-cats-redux-kernels-edition/test.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats-redux-kernels-edition/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../working/\"))\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Функции загрузки данных"},{"metadata":{"trusted":true},"cell_type":"code","source":"from random import shuffle\nfrom glob import glob\n\nIMG_SIZE = (224, 224)  # размер входного изображения сети\n\ntrain_files = glob('../working/train/*.jpg')\ntest_files = glob('../working/test/*.jpg')\n\n# загружаем входное изображение и предобрабатываем\ndef load_image(path, target_size=IMG_SIZE):\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, target_size)\n    return vgg16.preprocess_input(img)  # предобработка для VGG16\n\n# функция-генератор загрузки обучающих данных с диска\ndef fit_generator(files, batch_size=32):\n    batch_size = min(batch_size, len(files))\n    while True:\n        shuffle(files)\n        for k in range(len(files) // batch_size):\n            i = k * batch_size\n            j = i + batch_size\n            if j > len(files):\n                j = - j % len(files)\n            x = np.array([load_image(path) for path in files[i:j]])\n            y = np.array([1. if os.path.basename(path).startswith('dog') else 0.\n                          for path in files[i:j]])\n            yield (x, y)\n\n# функция-генератор загрузки тестовых изображений с диска\ndef predict_generator(files):\n    while True:\n        for path in files:\n            yield np.array([load_image(path)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_files","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Визуализируем примеры для обучения"},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nfrom matplotlib import pyplot as plt\nfig = plt.figure(figsize=(16, 8))\nfor i, path in enumerate(train_files[:10], 1):\n    subplot = fig.add_subplot(2, 5, i)\n    subplot.set_title('%s' % path.split('/')[-1])\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, IMG_SIZE)\n    plt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Загружаем предобученную модель"},{"metadata":{"trusted":true},"cell_type":"code","source":"# base_model - объект класса keras.models.Model (Functional Model)\nbase_model = vgg16.VGG16(weights='imagenet',\n                         include_top=False,\n                         input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = tf.keras.applications.ResNet50(\n    include_top=False, weights='imagenet', input_tensor=None,\n    input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3), pooling=None, classes=2\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Добавляем полносвязный слой"},{"metadata":{"trusted":true},"cell_type":"code","source":"# фиксируем все веса предобученной сети\nfor layer in base_model.layers:\n    layer.trainable = False\n\nx = base_model.layers[-5].output\nx = tf.keras.layers.Flatten()(x)\nx = tf.keras.layers.Dense(1,  # один выход (бинарная классификация)\n                          activation='sigmoid',  # функция активации  \n                          kernel_regularizer=tf.keras.regularizers.l1(1e-4))(x)\n\nmodel = tf.keras.Model(inputs=base_model.input, outputs=x, name='dogs_vs_cats')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Выводим архитектуру модели"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Компилируем модель и запускаем обучение"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam', \n              loss='binary_crossentropy',  # функция потерь binary_crossentropy (log loss\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"scrolled":false,"trusted":true},"cell_type":"code","source":"val_samples = 50  # число изображений в валидационной выборке\n\nshuffle(train_files)  # перемешиваем обучающую выборку\nvalidation_data = next(fit_generator(train_files[:val_samples], val_samples))\ntrain_data = fit_generator(train_files[val_samples:])  # данные читаем функцией-генератором\n\n# запускаем процесс обучения\nmodel.fit(train_data,\n          steps_per_epoch=10,  # число вызовов генератора за эпоху\n          epochs=30,  # число эпох обучения\n          validation_data=validation_data)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Предсказания на проверочной выборке"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_pred = model.predict(\n    predict_generator(test_files), steps=len(test_files))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('cats-dogs-vgg16.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(16, 8))\nfor i, (path, score) in enumerate(zip(test_files[:10], test_pred[:10]), 1):\n    subplot = fig.add_subplot(2, 5, i)\n    subplot.set_title('%.2f %s' % (score, os.path.basename(path)))\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, IMG_SIZE)\n    subplot.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Готовим данные для отправки"},{"metadata":{"trusted":true},"cell_type":"code","source":"import re\n\nwith open('submit.txt', 'w') as dst:\n    dst.write('id,label\\n')\n    for path, score in zip(test_files, test_pred):\n        dst.write('%s,%f\\n' % (re.search('(\\d+).jpg$', path).group(1), score))","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# LogLoss = 1.04979","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":4}