{"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_minor":4,"nbformat":4,"cells":[{"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())","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-12-18T19:51:45.998864Z","iopub.execute_input":"2021-12-18T19:51:45.999419Z","iopub.status.idle":"2021-12-18T19:51:46.004990Z","shell.execute_reply.started":"2021-12-18T19:51:45.999382Z","shell.execute_reply":"2021-12-18T19:51:46.004132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:52:07.122578Z","iopub.execute_input":"2021-12-18T19:52:07.122858Z","iopub.status.idle":"2021-12-18T19:52:18.259952Z","shell.execute_reply.started":"2021-12-18T19:52:07.122806Z","shell.execute_reply":"2021-12-18T19:52:18.259169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip ../input/dogs-vs-cats-redux-kernels-edition/test.zip","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:52:49.048243Z","iopub.execute_input":"2021-12-18T19:52:49.048522Z","iopub.status.idle":"2021-12-18T19:52:55.906688Z","shell.execute_reply.started":"2021-12-18T19:52:49.048490Z","shell.execute_reply":"2021-12-18T19:52:55.905814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nfrom random import shuffle\nfrom glob import glob\n\nIMG_SIZE = (224, 224)  # размер входного изображения сети\n\ntrain_files = glob('train/*.jpg')\ntest_files = glob('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)])","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:21.784346Z","iopub.execute_input":"2021-12-18T19:53:21.784916Z","iopub.status.idle":"2021-12-18T19:53:21.913806Z","shell.execute_reply.started":"2021-12-18T19:53:21.784876Z","shell.execute_reply":"2021-12-18T19:53:21.913093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:23.661874Z","iopub.execute_input":"2021-12-18T19:53:23.662521Z","iopub.status.idle":"2021-12-18T19:53:25.346209Z","shell.execute_reply.started":"2021-12-18T19:53:23.662485Z","shell.execute_reply":"2021-12-18T19:53:25.341102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = vgg16.VGG16(weights='imagenet',\n                         include_top=False,\n                         input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:32.210792Z","iopub.execute_input":"2021-12-18T19:53:32.211369Z","iopub.status.idle":"2021-12-18T19:53:32.488588Z","shell.execute_reply.started":"2021-12-18T19:53:32.211329Z","shell.execute_reply":"2021-12-18T19:53:32.487869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# фиксируем все веса предобученной сети\nfor layer in base_model.layers:\n    layer.trainable = False\n\nx = base_model.layers[-2].output\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPooling2D(2,2)(x)\nx = tf.keras.layers.Flatten()(x)\nx = tf.keras.layers.Dense(256, activation='relu')(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')","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:33.490205Z","iopub.execute_input":"2021-12-18T19:53:33.490457Z","iopub.status.idle":"2021-12-18T19:53:33.529816Z","shell.execute_reply.started":"2021-12-18T19:53:33.490429Z","shell.execute_reply":"2021-12-18T19:53:33.529186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:36.189811Z","iopub.execute_input":"2021-12-18T19:53:36.190376Z","iopub.status.idle":"2021-12-18T19:53:36.207889Z","shell.execute_reply.started":"2021-12-18T19:53:36.190338Z","shell.execute_reply":"2021-12-18T19:53:36.207198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam', \n              loss='binary_crossentropy',  # функция потерь binary_crossentropy (log loss\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:37.074422Z","iopub.execute_input":"2021-12-18T19:53:37.074852Z","iopub.status.idle":"2021-12-18T19:53:37.088005Z","shell.execute_reply.started":"2021-12-18T19:53:37.074790Z","shell.execute_reply":"2021-12-18T19:53:37.087154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from random import shuffle\n\n","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:53:38.053664Z","iopub.execute_input":"2021-12-18T19:53:38.053943Z","iopub.status.idle":"2021-12-18T19:53:38.058419Z","shell.execute_reply.started":"2021-12-18T19:53:38.053914Z","shell.execute_reply":"2021-12-18T19:53:38.057630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_samples = 5  # число изображений в валидационной выборке\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=100,  # число эпох обучения\n          validation_data=validation_data)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:54:14.277458Z","iopub.execute_input":"2021-12-18T19:54:14.277855Z","iopub.status.idle":"2021-12-18T19:56:49.817281Z","shell.execute_reply.started":"2021-12-18T19:54:14.277784Z","shell.execute_reply":"2021-12-18T19:56:49.816573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('cats-dogs-vgg16.hdf5')","metadata":{"execution":{"iopub.status.busy":"2021-12-18T19:57:09.346341Z","iopub.execute_input":"2021-12-18T19:57:09.346642Z","iopub.status.idle":"2021-12-18T19:57:09.652135Z","shell.execute_reply.started":"2021-12-18T19:57:09.346608Z","shell.execute_reply":"2021-12-18T19:57:09.651402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred = model.predict(\n    predict_generator(test_files), steps=len(test_files))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:00:31.107962Z","iopub.execute_input":"2021-12-18T20:00:31.108612Z","iopub.status.idle":"2021-12-18T20:01:38.961585Z","shell.execute_reply.started":"2021-12-18T20:00:31.108571Z","shell.execute_reply":"2021-12-18T20:01:38.960822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:01:58.649193Z","iopub.execute_input":"2021-12-18T20:01:58.649698Z","iopub.status.idle":"2021-12-18T20:01:58.655094Z","shell.execute_reply.started":"2021-12-18T20:01:58.649646Z","shell.execute_reply":"2021-12-18T20:01:58.654235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:02:07.914752Z","iopub.execute_input":"2021-12-18T20:02:07.915439Z","iopub.status.idle":"2021-12-18T20:02:09.218564Z","shell.execute_reply.started":"2021-12-18T20:02:07.915403Z","shell.execute_reply":"2021-12-18T20:02:09.217893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:02:40.637044Z","iopub.execute_input":"2021-12-18T20:02:40.637313Z","iopub.status.idle":"2021-12-18T20:02:40.683705Z","shell.execute_reply.started":"2021-12-18T20:02:40.637282Z","shell.execute_reply":"2021-12-18T20:02:40.683052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}