{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil\nimport matplotlib.pyplot as plt\nimport random\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2\nimport os\nimport zipfile\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"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 in \n\n# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n# import cv2\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nfrom os import getcwd\ntrain = f\"{getcwd()}/../kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\"\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**For extracting train images**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# os.mkdir('/kaggle/working/train')\nlocal_train = train\nz = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\", 'r')\nz.extractall('/kaggle/working')\nz.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**For extracting test images**"},{"metadata":{"trusted":true},"cell_type":"code","source":"local_train = train\nz = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\", 'r')\nz.extractall('/kaggle/working')\nz.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#v 3.0 r1.0\nsource = \"/kaggle/working/train/\"\nos.mkdir(\"/kaggle/working/training\")\nos.mkdir(\"/kaggle/working/training/cats\")\nos.mkdir(\"/kaggle/working/training/dogs\")\nos.mkdir(\"/kaggle/working/dev\")\nos.mkdir(\"/kaggle/working/dev/cats\")\nos.mkdir(\"/kaggle/working/dev/dogs\")\n\ndataset=[]\nfor i in os.listdir(source):\n    dataset.append(i)\n\nshuffled_set = random.sample(dataset, len(dataset))\n\ndev_length = int(len(dataset)*0.1)\ntrain_length = int(len(dataset) - dev_length) \ntraining_dirs = shuffled_set[:train_length]\ndev_dirs = shuffled_set[-dev_length:]\n\nfor i in training_dirs:\n    if 'cat' in i:\n        shutil.copyfile(source + i, \"/kaggle/working/training/cats/\" + i)\n    else:\n        shutil.copyfile(source + i, \"/kaggle/working/training/dogs/\" + i)\nfor i in dev_dirs:\n    if 'cat' in i:\n        shutil.copyfile(source + i, \"/kaggle/working/dev/cats/\" + i)\n    else:\n        shutil.copyfile(source + i, \"/kaggle/working/dev/dogs/\" + i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#V 3.0 r1.0\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), input_shape = (224,224,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(32, (3,3), activation = 'relu'),\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(64, (3,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(128, activation = 'relu'),\n    tf.keras.layers.Dense(1, activation = 'sigmoid')\n])\nmodel.summary()\nmodel.compile(loss = 'binary_crossentropy', optimizer='adam', metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_length, dev_length)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# V 3.0 r1.0\ntrain_datagen = ImageDataGenerator(rescale = 1.0/ 255.0)\ntrain_generator = train_datagen.flow_from_directory(\n    \"/kaggle/working/training\",\n    batch_size = 10,\n    class_mode = 'binary',\n    target_size = (224,224)\n)\ndev_datagen = ImageDataGenerator(rescale = 1.0/ 255.0)\ndev_generator = dev_datagen.flow_from_directory(\n    \"/kaggle/working/dev\",\n    batch_size = 10,\n    class_mode = 'binary',\n    target_size = (224,224)\n)\nhistory = model.fit_generator(train_generator, epochs = 10, verbose =1, validation_data = dev_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.image  as mpimg\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(len(acc))\n\n#______________________\n#Accuracy comparision\n#______________________\n\nplt.plot(epochs, acc, 'r', \"Training Accuracy\")\nplt.plot(epochs, val_acc,'b', \"dev Accuracy\")\nplt.title(\"Training and dev Accuracy\")\nplt.legend(loc=0)\nplt.figure()\n\n#_____________________________\n#Loss comparision\n#_____________________________\n\nplt.plot(epochs, loss, 'r', \"Training loss\")\nplt.plot(epochs, val_loss, 'b', \"Dev loss\")\nplt.title(\"Training and dev loss\")\nplt.legend(loc=0)\n# plt.figure()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('fmodel.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir(\"/kaggle/working/testing\")\nos.mkdir(\"/kaggle/working/testing/test\")\nfor i in os.listdir(\"/kaggle/working/test\"):\n    shutil.copyfile(\"/kaggle/working/test/\" + i, \"/kaggle/working/testing/test/\" + i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1.0/ 255.0)\ntest_generator = test_datagen.flow_from_directory(\n    \"/kaggle/working/testing\",\n    target_size = (224,224),\n    batch_size = 10,\n    class_mode = 'binary'\n)\npreds = model.predict(test_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load_m = tf.keras.models.load_model('/kaggle/input/my-model/fmodel.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load_m.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pred = load_m.predict_generator(test_generator, max_queue_size = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.save_weights('smodel_weights.h5')\n# model.save('smodel.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"counter = range(1, 12500 + 1)\nsolution = pd.DataFrame({\"id\": counter, \"label\":list(preds)})\ncols = ['label']\n\nfor col in cols:\n    solution[col] = solution[col].map(lambda x: str(x).lstrip('[').rstrip(']')).astype(float)\n\nsolution.to_csv(\"dogsVScats.csv\", index = False)","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}