{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-27T12:50:56.429627Z","iopub.execute_input":"2022-03-27T12:50:56.429925Z","iopub.status.idle":"2022-03-27T12:50:56.457278Z","shell.execute_reply.started":"2022-03-27T12:50:56.429852Z","shell.execute_reply":"2022-03-27T12:50:56.456621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Распаковка данных и формирование структуры папок дынных","metadata":{}},{"cell_type":"code","source":"import zipfile\npath_to_zip_file='/kaggle/input/dogs-vs-cats/train.zip'\ndirectory_to_extract_to='/kaggle/working/dogs_vs_cats/'\nwith zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:\n    zip_ref.extractall(directory_to_extract_to)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:50:56.465948Z","iopub.execute_input":"2022-03-27T12:50:56.466435Z","iopub.status.idle":"2022-03-27T12:51:07.391332Z","shell.execute_reply.started":"2022-03-27T12:50:56.466399Z","shell.execute_reply":"2022-03-27T12:51:07.390513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !pip install pycocotools --user","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:07.393590Z","iopub.execute_input":"2022-03-27T12:51:07.394015Z","iopub.status.idle":"2022-03-27T12:51:07.398803Z","shell.execute_reply.started":"2022-03-27T12:51:07.393947Z","shell.execute_reply":"2022-03-27T12:51:07.397860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, shutil\nfrom keras import layers\nfrom keras import models\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.applications import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import optimizers","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:07.400324Z","iopub.execute_input":"2022-03-27T12:51:07.401281Z","iopub.status.idle":"2022-03-27T12:51:11.986004Z","shell.execute_reply.started":"2022-03-27T12:51:07.401241Z","shell.execute_reply":"2022-03-27T12:51:11.985276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mk_dir_func(dir):\n    try:\n        os.mkdir(dir)\n    except:\n        pass","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:11.987895Z","iopub.execute_input":"2022-03-27T12:51:11.988230Z","iopub.status.idle":"2022-03-27T12:51:11.994085Z","shell.execute_reply.started":"2022-03-27T12:51:11.988191Z","shell.execute_reply":"2022-03-27T12:51:11.993346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"original_dataset_dir='/kaggle/working/dogs_vs_cats/train/'\n\nbase_dir = '/kaggle/working/cats_and_dogs_small'\n\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\ntest_dir = os.path.join(base_dir, 'test')\n\ntrain_cats_dir = os.path.join(train_dir, 'cats')\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\n\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\n\ntest_cats_dir = os.path.join(test_dir, 'cats')\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\n\nmk_dir_func(base_dir)\nmk_dir_func(train_dir)\nmk_dir_func(validation_dir)\nmk_dir_func(test_dir)\nmk_dir_func(train_cats_dir)\nmk_dir_func(train_dogs_dir)\nmk_dir_func(validation_cats_dir)\nmk_dir_func(validation_dogs_dir)\nmk_dir_func(test_cats_dir)\nmk_dir_func(test_dogs_dir)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:11.996002Z","iopub.execute_input":"2022-03-27T12:51:11.996454Z","iopub.status.idle":"2022-03-27T12:51:12.015050Z","shell.execute_reply.started":"2022-03-27T12:51:11.996319Z","shell.execute_reply":"2022-03-27T12:51:12.014244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(train_cats_dir, i)\n    shutil.copyfile(src,dst)\n    \nfnames = ['cat.{}.jpg'.format(i) for i in range(1000,1500)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(validation_cats_dir, i)\n    shutil.copyfile(src,dst)\n\nfnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(test_cats_dir, i)\n    shutil.copyfile(src,dst)\n    \nfnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(train_dogs_dir, i)\n    shutil.copyfile(src,dst)\n    \nfnames = ['dog.{}.jpg'.format(i) for i in range(1000,1500)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(validation_dogs_dir, i)\n    shutil.copyfile(src,dst)\n\nfnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor i in fnames:\n    src = os.path.join(original_dataset_dir, i)\n    dst = os.path.join(test_dogs_dir, i)\n    shutil.copyfile(src,dst)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:12.016087Z","iopub.execute_input":"2022-03-27T12:51:12.016289Z","iopub.status.idle":"2022-03-27T12:51:12.429915Z","shell.execute_reply.started":"2022-03-27T12:51:12.016266Z","shell.execute_reply":"2022-03-27T12:51:12.429138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Загрузка предобученной сети и формирование новой сети на базе предобученной.","metadata":{}},{"cell_type":"code","source":"conv_base = VGG16(weights='imagenet',\n                 include_top=False,\n                 input_shape=(150,150,3))","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:12.430972Z","iopub.execute_input":"2022-03-27T12:51:12.431204Z","iopub.status.idle":"2022-03-27T12:51:15.491236Z","shell.execute_reply.started":"2022-03-27T12:51:12.431171Z","shell.execute_reply":"2022-03-27T12:51:15.490488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"conv_base.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:15.494269Z","iopub.execute_input":"2022-03-27T12:51:15.494484Z","iopub.status.idle":"2022-03-27T12:51:15.511105Z","shell.execute_reply.started":"2022-03-27T12:51:15.494459Z","shell.execute_reply":"2022-03-27T12:51:15.510405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:15.514012Z","iopub.execute_input":"2022-03-27T12:51:15.514210Z","iopub.status.idle":"2022-03-27T12:51:15.588401Z","shell.execute_reply.started":"2022-03-27T12:51:15.514186Z","shell.execute_reply":"2022-03-27T12:51:15.587724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Заморозка предобученного сверточного слоя","metadata":{}},{"cell_type":"code","source":"conv_base.trainable = False\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:15.591578Z","iopub.execute_input":"2022-03-27T12:51:15.591767Z","iopub.status.idle":"2022-03-27T12:51:15.601178Z","shell.execute_reply.started":"2022-03-27T12:51:15.591743Z","shell.execute_reply":"2022-03-27T12:51:15.600478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Инициализация генераторов данных с расширением данных.","metadata":{}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale= 1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest')\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150,150),\n    batch_size=20,\n    class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n    validation_dir,\n    target_size=(150,150),\n    batch_size=20,\n    class_mode='binary')\n\nmodel.compile(loss='binary_crossentropy',\n             optimizer=optimizers.RMSprop(learning_rate=2e-5),\n             metrics=['acc'])\n","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:15.602437Z","iopub.execute_input":"2022-03-27T12:51:15.602744Z","iopub.status.idle":"2022-03-27T12:51:15.827179Z","shell.execute_reply.started":"2022-03-27T12:51:15.602706Z","shell.execute_reply":"2022-03-27T12:51:15.826517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    steps_per_epoch=100,\n    epochs=30,\n    validation_data=validation_generator,\n    validation_steps=50)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:51:15.828221Z","iopub.execute_input":"2022-03-27T12:51:15.828462Z","iopub.status.idle":"2022-03-27T13:00:15.952881Z","shell.execute_reply.started":"2022-03-27T12:51:15.828429Z","shell.execute_reply":"2022-03-27T13:00:15.952110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc)+1)\nplt.figure(figsize=(17,6))\n\nplt.subplot(1,2,1)\nplt.plot(epochs, acc, 'bo', label = 'Training acc')\nplt.plot(epochs, val_acc, 'b', label = 'Validation acc')\nplt.title('Training and Validation accuracy')\nplt.grid()\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and Validation loss')\nplt.grid()\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T13:00:15.954340Z","iopub.execute_input":"2022-03-27T13:00:15.954855Z","iopub.status.idle":"2022-03-27T13:00:16.358922Z","shell.execute_reply.started":"2022-03-27T13:00:15.954812Z","shell.execute_reply":"2022-03-27T13:00:16.358221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Дообучение","metadata":{}},{"cell_type":"markdown","source":"## Разморозка верхних слоев сверточной сети","metadata":{}},{"cell_type":"code","source":"conv_base.trainable = True\nset_trainable = False\nfor layer in conv_base.layers:\n    if layer.name == 'block5_conv1':\n        set_trainable = True\n    if set_trainable:\n        layer.trainable = True\n    else:\n        layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-03-27T13:00:20.095063Z","iopub.execute_input":"2022-03-27T13:00:20.095482Z","iopub.status.idle":"2022-03-27T13:00:20.102476Z","shell.execute_reply.started":"2022-03-27T13:00:20.095437Z","shell.execute_reply":"2022-03-27T13:00:20.101584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='binary_crossentropy',\n             optimizer=optimizers.RMSprop(learning_rate=1e-5),\n             metrics=['acc'])\n\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=100,\n    epochs=100,\n    validation_data=validation_generator,\n    validation_steps=50)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T13:00:56.342458Z","iopub.execute_input":"2022-03-27T13:00:56.342727Z","iopub.status.idle":"2022-03-27T13:30:58.472133Z","shell.execute_reply.started":"2022-03-27T13:00:56.342697Z","shell.execute_reply":"2022-03-27T13:30:58.471426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc)+1)\nplt.figure(figsize=(17,6))\n\nplt.subplot(1,2,1)\nplt.plot(epochs, acc, 'bo', label = 'Training acc')\nplt.plot(epochs, val_acc, 'b', label = 'Validation acc')\nplt.title('Training and Validation accuracy')\nplt.grid()\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and Validation loss')\nplt.grid()\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T13:30:58.474238Z","iopub.execute_input":"2022-03-27T13:30:58.474513Z","iopub.status.idle":"2022-03-27T13:30:58.855012Z","shell.execute_reply.started":"2022-03-27T13:30:58.474475Z","shell.execute_reply":"2022-03-27T13:30:58.854247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2022-03-27T13:00:16.360123Z","iopub.execute_input":"2022-03-27T13:00:16.360459Z","iopub.status.idle":"2022-03-27T13:00:16.364669Z","shell.execute_reply.started":"2022-03-27T13:00:16.360421Z","shell.execute_reply":"2022-03-27T13:00:16.363639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}