{"cells":[{"metadata":{"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# You can write up to 5GB 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 zipfile\nwith zipfile.ZipFile('../input/dogs-vs-cats/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('kaggle/working/Train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('../input/dogs-vs-cats/test1.zip','r') as zip_ref:\n    zip_ref.extractall('kaggle/working/Test')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport tensorflow as tf\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# detect and init the TPU\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\n\n# instantiate a distribution strategy\ntpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dir = os.listdir('kaggle/working/Train/train')\nprint(dir[:6])\nlabel = [1 if files.split('.')[0] == 'dog' else 0 for files in dir]\ndf = pd.DataFrame({'file' : dir, 'label' : label})\nprint(df.head())\nprint(df['label'].value_counts())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#printing random image\nfile = random.choice(dir)\nimage = load_img('kaggle/working/Train/train/' + file)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Img_width = 128\nImg_length = 128\nImg_size = (Img_width, Img_length)\nImg_channels = 3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nwith tpu_strategy.scope():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation = 'relu', input_shape = (Img_width, Img_length, Img_channels)))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size = (2, 2)))\n    model.add(Dropout(0.25))\n    \n    model.add(Conv2D(64, (3, 3), activation = 'relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size = (2, 2)))\n    model.add(Dropout(0.25))\n           \n    model.add(Conv2D(128, (3, 3), activation = 'relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size = (2, 2)))\n    model.add(Dropout(0.25))    \n          \n    model.add(Flatten())\n    model.add(Dense(512, activation = 'relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n\n    model.add(Dense(2, activation = 'softmax'))\n          \n    model.compile(loss = 'categorical_crossentropy', optimizer = 'Adam', metrics = ['accuracy'])\n    model.summary()\n\n          ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping\n\nearlystop = EarlyStopping(monitor = 'val_loss', patience = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Converting labels back to cat/dogs to be used in imageGenerator\ndf['label'] = df['label'].replace({1 : 'dog', 0 : 'cat'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size = 0.2, random_state = 2)\ntrain_df = train_df.reset_index(drop = True)\nvalidate_df = validate_df.reset_index(drop = True) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_size = train_df.shape[0]\nprint(train_size)\nvalidate_size = validate_df.shape[0]\nprint(validate_size)\nbatch_size = 128","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_img_gen = ImageDataGenerator(rotation_range = 20,\n                                   rescale = 1./255,\n                                   shear_range = 0.1, \n                                   zoom_range = 0.2, \n                                   horizontal_flip = True,\n                                   width_shift_range = 0.1,\n                                   height_shift_range = 0.1)\ntrain_generator = train_img_gen.flow_from_dataframe(train_df, \n                                                    'kaggle/working/Train/train',\n                                                    x_col = 'file',\n                                                    y_col = 'label',\n                                                    target_size = Img_size,\n                                                   class_mode = 'categorical',\n                                                   batch_size = batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate_img_gen = ImageDataGenerator(rescale = 1./255)\nvalidate_generator = validate_img_gen.flow_from_dataframe(validate_df, \n                                                          'kaggle/working/Train/train', \n                                                          x_col = 'file',\n                                                          y_col = 'label',\n                                                          target_size = Img_size,\n                                                          class_mode = 'categorical',\n                                                          batch_size = batch_size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Cheking the image generator\nexample_df = train_df.sample(n = 1).reset_index(drop = True)\nexample_generator  = train_img_gen.flow_from_dataframe(example_df, 'kaggle/working/Train/train', \n                                                       x_col = 'file', y_col = 'label',\n                                                       target_size = Img_size,\n                                                       class_mode = 'categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (12, 12))\nfor i in range(0,12):\n    plt.subplot(4, 3, i+1)\n    for x, y in example_generator:\n        img = x[0]\n        plt.imshow(img)\n        break\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 28\nfit = model.fit_generator(train_generator, \n                          epochs = epochs, \n                          validation_data = validate_generator, \n                          validation_steps = validate_size//batch_size,\n                          steps_per_epoch = train_size//batch_size,\n                         callbacks = [earlystop])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('cat-dogs-pk.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_file_dir = os.listdir('kaggle/working/Test/test1')\ntest_df = pd.DataFrame({\n    'file' : test_file_dir\n})\ntest_size = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_img_gen = ImageDataGenerator(rescale = 1./255)\ntest_generator = test_img_gen.flow_from_dataframe(test_df, \n                                                  'kaggle/working/Test/test1',\n                                                  x_col = 'file',\n                                                  y_col = None,\n                                                  class_mode = None,\n                                                  target_size = Img_size,\n                                                  batch_size = batch_size,\n                                                  shuffle = False)\n                                                  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps = np.ceil(test_size/batch_size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['cat'] = np.argmax(predict, axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_map = dict((v, k) for k,v in train_generator.class_indices.items())\ntest_df['cat'] = test_df['cat'].replace(label_map)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['cat'] = test_df['cat'].replace({'dog' : 1, 'cat' : 0})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df = test_df.copy()\nsub_df['id'] = sub_df['file'].str.split('.').str[0]\nsub_df['label'] = sub_df['cat']\nsub_df.drop(['file', 'cat'], axis = 1, inplace = True)\nsub_df.to_csv('submission.csv', index = False)","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}