{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Импортируем нужные библиотеки**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport random\n\nimport matplotlib.pyplot as plt\n\nimport os\nimport zipfile\n\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* Извлечение zip-файла"},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip = '/kaggle/input/dogs-vs-cats/train.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = '/tmp/train'\nimg_names = os.listdir(os.path.join(base_dir))\nimg_names[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = random.choice(img_names)\nimage = load_img(\"/tmp/train/\"+sample)\nplt.imshow(image)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Подготовка данных**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# установим метку собака и кошка для изображений\nlabel = []\n\nfor i in img_names:\n    if(i.split(\".\")[0] == \"dog\"):\n        label.append(\"Dog\")\n    else:\n        label.append(\"Cat\")\n\nlabel[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.DataFrame({\"Image\" : img_names, \"Label\" : label})\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.Label.value_counts().plot.bar(color = ['yellow','green'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size = 0.2)\ntrain_df = train_df.reset_index(drop = True)\nvalidate_df = validate_df.reset_index(drop = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Построим модель**\n\n* Conv Layer: этот слой будет извлекать важные объекты из изображения\n* Pooling Layer: этот слой уменьшает пространственный объем входного изображения после свертки, изолируя важные объекты\n* Hidden Layer: Он соединяет сеть от одного слоя к другому слою\n* Output Layer: это конечный слой с нейронами, равными количеству классов"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    \n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='relu'),\n    \n    tf.keras.layers.Dense(1, activation='sigmoid')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = 'binary_crossentropy',\n              optimizer = 'SGD',\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Обучающий генератор с увеличением изображения\ntrain_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')\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"/tmp/train/\", \n    x_col='Image',\n    y_col='Label',\n    target_size = (150, 150),\n    class_mode = 'binary',\n    batch_size = 20\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#validation generator\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"/tmp/train/\", \n    x_col='Image',\n    y_col='Label',\n    target_size = (150, 150),\n    class_mode = 'binary',\n    batch_size = 20\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nlocal_zip = '/kaggle/input/dogs-vs-cats/test1.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()\n\ntest_dir = '/tmp/test1/'\ntest_img = os.listdir(os.path.join(test_dir))\ntest_img[:10]\n\ntest_df = pd.DataFrame({'Image': test_img})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"/tmp/test1/\", \n    x_col = 'Image',\n    y_col = None,\n    class_mode = None,\n    target_size = (150, 150),\n    batch_size = 20,\n    shuffle = False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps = np.ceil(12500/20))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def label(predict):\n    if(predict > 0.5):\n        return \"Dog\"\n    else:\n        return \"Cat\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Label'] = predict\ntest_df['Label'] = test_df['Label'].apply(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.Label.value_counts().plot.bar(color = ['red','blue'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"v = random.randint(0, 12000)\n\nsample_test = test_df.iloc[v:(v+18)].reset_index(drop = True)\nsample_test.head()\n\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['Image']\n    category = row['Label']\n    img = load_img(\"/tmp/test1/\" + filename, target_size = (150, 150))\n    plt.subplot(6, 3, index + 1)\n    plt.imshow(img)\n    plt.xlabel(filename + ' ( ' + \"{}\".format(category) + ' )' )\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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":4}