{"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-07-10T04:44:29.574024Z","iopub.execute_input":"2022-07-10T04:44:29.574629Z","iopub.status.idle":"2022-07-10T04:44:29.600664Z","shell.execute_reply.started":"2022-07-10T04:44:29.574534Z","shell.execute_reply":"2022-07-10T04:44:29.599841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load all libraries needed\nimport pandas\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport cv2 \nimport zipfile\nimport glob\nimport os\nimport shutil\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Input, Dense, Dropout, Flatten, MaxPool2D\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:44:33.568063Z","iopub.execute_input":"2022-07-10T04:44:33.570024Z","iopub.status.idle":"2022-07-10T04:44:39.858838Z","shell.execute_reply.started":"2022-07-10T04:44:33.569970Z","shell.execute_reply":"2022-07-10T04:44:39.857880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check for gpus available\nprint('GPU name: ', tf.config.experimental.list_physical_devices('GPU'))","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:44:39.860760Z","iopub.execute_input":"2022-07-10T04:44:39.861404Z","iopub.status.idle":"2022-07-10T04:44:40.024764Z","shell.execute_reply.started":"2022-07-10T04:44:39.861357Z","shell.execute_reply":"2022-07-10T04:44:40.022530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# extract all zip files\nfor file_zip in glob.glob('/kaggle/input/dogs-vs-cats-redux-kernels-edition/*.zip'):\n    with zipfile.ZipFile(file_zip, 'r') as zip_ref:\n        zip_ref.extractall()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:44:40.026344Z","iopub.execute_input":"2022-07-10T04:44:40.027303Z","iopub.status.idle":"2022-07-10T04:44:57.472457Z","shell.execute_reply.started":"2022-07-10T04:44:40.027261Z","shell.execute_reply":"2022-07-10T04:44:57.471509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display first 100 images\ndef plot_images(rows, columns, images):\n    '''\n    Plot first 100 images\n    INPUTS:\n        rows: number of rows we want to display images on it\n        columns: number of images we want to display in each row\n        images: consist of 100 images each image consist 224*224 pixels\n        labels: truth value for each image\n    '''\n    \n    fig, x= plt.subplots(rows, columns, constrained_layout=True,figsize=(15,8))\n    plt.setp(x, xticks=[], yticks=[])\n    for i in range (len(x)):\n        for j in range (len(x[0])):\n            index = i*columns+j\n            img = cv2.imread('train/' + images[index])\n            x[i,j].imshow(cv2.resize(img, (224, 224)))\n            \nnum_columns = 10\ntrain_data = os.listdir('train/')[:100]\nplot_images(num_columns, num_columns, train_data)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:44:57.477038Z","iopub.execute_input":"2022-07-10T04:44:57.477309Z","iopub.status.idle":"2022-07-10T04:45:04.124240Z","shell.execute_reply.started":"2022-07-10T04:44:57.477284Z","shell.execute_reply":"2022-07-10T04:45:04.123408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare train data for using ImageDataGenerator\nbase_path = '/kaggle/working/train/'\ncategories = ['CAT' , 'DOG']\ndef move_images_to_specific_folder(file_path, category):\n    for image_name in os.listdir(file_path):\n        if category.lower() in image_name:\n            shutil.move(os.path.join(base_path, image_name), os.path.join(base_path, category))\n    \n# create file for cats and another one for dogs\nfor category in categories:\n    path = os.path.join(base_path, category)\n    os.mkdir(path)\n\n# move cat images and dog images for folders\nfor category in categories:\n    move_images_to_specific_folder(base_path, category)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:04.125512Z","iopub.execute_input":"2022-07-10T04:45:04.125854Z","iopub.status.idle":"2022-07-10T04:45:05.180231Z","shell.execute_reply.started":"2022-07-10T04:45:04.125819Z","shell.execute_reply":"2022-07-10T04:45:05.179266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create ImageDataGenerator to apply preprocessing for images and split data to batches to feed it to training in same time save memory\nimage_size = 224\nbatch_size = 64\nepochs = 100\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n                                   rotation_range=20,\n                                   validation_split=0.2,\n                                  horizontal_flip=True,\n                                   width_shift_range = 0.2,\n                                   height_shift_range = 0.2)\n\ntrain_generator = train_datagen.flow_from_directory('train/', class_mode='binary', batch_size = batch_size, target_size=(image_size,image_size), subset='training', shuffle=True, seed=42)\nvalidation_generator = train_datagen.flow_from_directory('train/', class_mode='binary', batch_size = batch_size, target_size=(image_size,image_size), subset='validation', shuffle=True, seed=42)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:05.181734Z","iopub.execute_input":"2022-07-10T04:45:05.182277Z","iopub.status.idle":"2022-07-10T04:45:06.480858Z","shell.execute_reply.started":"2022-07-10T04:45:05.182237Z","shell.execute_reply":"2022-07-10T04:45:06.479855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Design model architecture\ntf.random.set_seed(42)\nmodel = Sequential()\nmodel.add(Conv2D(input_shape=(224,224,3), filters = 32, kernel_size=(3,3), strides=(1,1), padding=('same'), activation=\"relu\"))\nmodel.add(Conv2D(filters = 64, kernel_size=(3,3), strides=(1,1), padding=('same'), activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters = 128, kernel_size=(3,3), strides=(2,2), padding=('same'), activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters = 256, kernel_size=(3,3), strides=(1,1), padding=('same'), activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters = 512, kernel_size=(3,3), strides=(1,1), padding=('same'), activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters = 1024, kernel_size=(2,2), strides=(1,1), padding=('same'), activation=\"relu\"))\nmodel.add(Flatten())\nmodel.add(Dense(units=4096,activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=4096,activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=1, activation=\"sigmoid\"))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:06.482293Z","iopub.execute_input":"2022-07-10T04:45:06.482893Z","iopub.status.idle":"2022-07-10T04:45:09.208073Z","shell.execute_reply.started":"2022-07-10T04:45:06.482853Z","shell.execute_reply":"2022-07-10T04:45:09.207095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:27.916997Z","iopub.execute_input":"2022-07-10T04:45:27.917445Z","iopub.status.idle":"2022-07-10T04:45:27.934246Z","shell.execute_reply.started":"2022-07-10T04:45:27.917406Z","shell.execute_reply":"2022-07-10T04:45:27.933369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)\nsave_best = ModelCheckpoint(\nfilepath = 'best_model.hdf5',\nverbose=1, save_best_only=True\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:37.701952Z","iopub.execute_input":"2022-07-10T04:45:37.702302Z","iopub.status.idle":"2022-07-10T04:45:37.707989Z","shell.execute_reply.started":"2022-07-10T04:45:37.702272Z","shell.execute_reply":"2022-07-10T04:45:37.706727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(train_generator, steps_per_epoch=train_generator.samples // batch_size, validation_data = validation_generator,\\\n                         validation_steps = validation_generator.samples // batch_size, epochs = epochs, callbacks=[save_best,early_stopping], verbose=2)","metadata":{"execution":{"iopub.status.busy":"2022-07-10T04:45:40.599385Z","iopub.execute_input":"2022-07-10T04:45:40.599786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = tf.keras.models.load_model('best_model.hdf5')\nbest_model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-09T00:03:05.850075Z","iopub.execute_input":"2022-07-09T00:03:05.850844Z","iopub.status.idle":"2022-07-09T00:03:14.442193Z","shell.execute_reply.started":"2022-07-09T00:03:05.850801Z","shell.execute_reply":"2022-07-09T00:03:14.441159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_image_files = os.listdir('/kaggle/working/test')\ntest_df = pd.DataFrame(data = test_image_files, columns = ['filename'])\ntest_df['id'] = test_df['filename'].apply(lambda f: int(f.split('.')[0]))\ntest_df.sort_values(by = 'id', inplace = True, ignore_index = True)","metadata":{"execution":{"iopub.status.busy":"2022-07-09T00:06:07.271917Z","iopub.execute_input":"2022-07-09T00:06:07.272295Z","iopub.status.idle":"2022-07-09T00:06:07.303364Z","shell.execute_reply.started":"2022-07-09T00:06:07.27226Z","shell.execute_reply":"2022-07-09T00:06:07.302493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale = 1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    '/kaggle/working/test', \n    x_col='filename',\n    class_mode= None,\n    target_size=(image_size,image_size),\n    batch_size=batch_size,\n    shuffle=False\n)\npredict = best_model.predict(test_generator, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-07-09T00:06:16.651452Z","iopub.execute_input":"2022-07-09T00:06:16.65217Z","iopub.status.idle":"2022-07-09T00:07:39.187582Z","shell.execute_reply.started":"2022-07-09T00:06:16.652132Z","shell.execute_reply":"2022-07-09T00:07:39.186409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"label\"] = predict\nresult = test_df[[\"id\", \"label\"]]\nresult.to_csv('submission_1.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-09T00:07:39.388807Z","iopub.execute_input":"2022-07-09T00:07:39.389408Z","iopub.status.idle":"2022-07-09T00:07:39.429927Z","shell.execute_reply.started":"2022-07-09T00:07:39.389368Z","shell.execute_reply":"2022-07-09T00:07:39.42906Z"},"trusted":true},"execution_count":null,"outputs":[]}]}