{"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":"2023-07-30T06:24:41.883912Z","iopub.execute_input":"2023-07-30T06:24:41.884372Z","iopub.status.idle":"2023-07-30T06:24:41.894204Z","shell.execute_reply.started":"2023-07-30T06:24:41.884338Z","shell.execute_reply":"2023-07-30T06:24:41.892699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd \n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\n%matplotlib inline\nimport seaborn as sns\nfrom PIL import Image, ImageFilter, ImageEnhance\nimport cv2\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nimport os\nfrom numpy import asarray\n\nimport zipfile\n\nzip_files = ['test1', 'train']\n\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:41.896407Z","iopub.execute_input":"2023-07-30T06:24:41.896816Z","iopub.status.idle":"2023-07-30T06:24:55.026787Z","shell.execute_reply.started":"2023-07-30T06:24:41.896753Z","shell.execute_reply":"2023-07-30T06:24:55.025861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR_PATH = './train'\nfile_names = os.listdir(TRAIN_DIR_PATH)\nprint('There are {} number of images in directory.'.format(len(file_names)))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.028125Z","iopub.execute_input":"2023-07-30T06:24:55.02866Z","iopub.status.idle":"2023-07-30T06:24:55.055192Z","shell.execute_reply.started":"2023-07-30T06:24:55.028624Z","shell.execute_reply":"2023-07-30T06:24:55.053627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import numpy as np\n#import pandas as pd \n#from keras.preprocessing.image \n#from tensorflow.keras.utils import load_img\n#import ImageDataGenerator, load_img\n#from keras.utils import to_categorical\n#from sklearn.model_selection import train_test_split\n#import matplotlib.pyplot as plt\n#import random\n#import os\n#print(os.listdir(\"../input\"))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.057831Z","iopub.execute_input":"2023-07-30T06:24:55.058253Z","iopub.status.idle":"2023-07-30T06:24:55.064143Z","shell.execute_reply.started":"2023-07-30T06:24:55.058206Z","shell.execute_reply":"2023-07-30T06:24:55.062735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.065734Z","iopub.execute_input":"2023-07-30T06:24:55.06617Z","iopub.status.idle":"2023-07-30T06:24:55.079353Z","shell.execute_reply.started":"2023-07-30T06:24:55.066137Z","shell.execute_reply":"2023-07-30T06:24:55.077999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#filenames = os.listdir(\"../input/train/train\")\nfilenames = os.listdir(TRAIN_DIR_PATH)\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\n\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.081339Z","iopub.execute_input":"2023-07-30T06:24:55.081745Z","iopub.status.idle":"2023-07-30T06:24:55.151417Z","shell.execute_reply.started":"2023-07-30T06:24:55.08171Z","shell.execute_reply":"2023-07-30T06:24:55.150058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.152865Z","iopub.execute_input":"2023-07-30T06:24:55.153228Z","iopub.status.idle":"2023-07-30T06:24:55.167434Z","shell.execute_reply.started":"2023-07-30T06:24:55.153198Z","shell.execute_reply":"2023-07-30T06:24:55.165755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.169607Z","iopub.execute_input":"2023-07-30T06:24:55.170512Z","iopub.status.idle":"2023-07-30T06:24:55.432088Z","shell.execute_reply.started":"2023-07-30T06:24:55.170464Z","shell.execute_reply":"2023-07-30T06:24:55.430851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(filenames)\n#image = load_img(\"../input/train/train/\"+sample)\nimage = load_img(\"./train/\"+sample)\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.437757Z","iopub.execute_input":"2023-07-30T06:24:55.438782Z","iopub.status.idle":"2023-07-30T06:24:55.497753Z","shell.execute_reply.started":"2023-07-30T06:24:55.438716Z","shell.execute_reply":"2023-07-30T06:24:55.495096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.49918Z","iopub.status.idle":"2023-07-30T06:24:55.499722Z","shell.execute_reply.started":"2023-07-30T06:24:55.4995Z","shell.execute_reply":"2023-07-30T06:24:55.499522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.501277Z","iopub.status.idle":"2023-07-30T06:24:55.501728Z","shell.execute_reply.started":"2023-07-30T06:24:55.501511Z","shell.execute_reply":"2023-07-30T06:24:55.501531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.504002Z","iopub.status.idle":"2023-07-30T06:24:55.504448Z","shell.execute_reply.started":"2023-07-30T06:24:55.504237Z","shell.execute_reply":"2023-07-30T06:24:55.504257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.505969Z","iopub.status.idle":"2023-07-30T06:24:55.507695Z","shell.execute_reply.started":"2023-07-30T06:24:55.507463Z","shell.execute_reply":"2023-07-30T06:24:55.507484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) \n\ntrain_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)\n\ntrain_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.508948Z","iopub.status.idle":"2023-07-30T06:24:55.510152Z","shell.execute_reply.started":"2023-07-30T06:24:55.50979Z","shell.execute_reply":"2023-07-30T06:24:55.509825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.511362Z","iopub.status.idle":"2023-07-30T06:24:55.51214Z","shell.execute_reply.started":"2023-07-30T06:24:55.51184Z","shell.execute_reply":"2023-07-30T06:24:55.511869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.514247Z","iopub.status.idle":"2023-07-30T06:24:55.514666Z","shell.execute_reply.started":"2023-07-30T06:24:55.514472Z","shell.execute_reply":"2023-07-30T06:24:55.514491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\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\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    #\"../input/train/train/\", \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.516347Z","iopub.status.idle":"2023-07-30T06:24:55.516738Z","shell.execute_reply.started":"2023-07-30T06:24:55.516546Z","shell.execute_reply":"2023-07-30T06:24:55.516563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    #\"../input/train/train/\", \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.518327Z","iopub.status.idle":"2023-07-30T06:24:55.519213Z","shell.execute_reply.started":"2023-07-30T06:24:55.518926Z","shell.execute_reply":"2023-07-30T06:24:55.518954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    #\"../input/train/train/\", \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.520995Z","iopub.status.idle":"2023-07-30T06:24:55.521409Z","shell.execute_reply.started":"2023-07-30T06:24:55.521212Z","shell.execute_reply":"2023-07-30T06:24:55.52123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(5, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.522346Z","iopub.status.idle":"2023-07-30T06:24:55.522745Z","shell.execute_reply.started":"2023-07-30T06:24:55.522545Z","shell.execute_reply":"2023-07-30T06:24:55.522564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.524044Z","iopub.status.idle":"2023-07-30T06:24:55.524435Z","shell.execute_reply.started":"2023-07-30T06:24:55.524239Z","shell.execute_reply":"2023-07-30T06:24:55.524257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, epochs, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, epochs, 1))\nax2.set_yticks(np.arange(0, 1, 0.1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.526053Z","iopub.status.idle":"2023-07-30T06:24:55.526475Z","shell.execute_reply.started":"2023-07-30T06:24:55.526269Z","shell.execute_reply":"2023-07-30T06:24:55.52629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test_filenames = os.listdir(\"../input/test1/test1\")\ntest_filenames = os.listdir(\"./test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.529778Z","iopub.status.idle":"2023-07-30T06:24:55.530247Z","shell.execute_reply.started":"2023-07-30T06:24:55.530037Z","shell.execute_reply":"2023-07-30T06:24:55.530057Z"},"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    #\"../input/test1/test1/\", \n    \"./test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=IMAGE_SIZE,\n    batch_size=batch_size,\n    shuffle=False\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.531832Z","iopub.status.idle":"2023-07-30T06:24:55.532252Z","shell.execute_reply.started":"2023-07-30T06:24:55.532054Z","shell.execute_reply":"2023-07-30T06:24:55.532073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict(test_generator, steps=np.ceil(nb_samples/batch_size))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.533821Z","iopub.status.idle":"2023-07-30T06:24:55.534218Z","shell.execute_reply.started":"2023-07-30T06:24:55.534026Z","shell.execute_reply":"2023-07-30T06:24:55.534045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.535647Z","iopub.status.idle":"2023-07-30T06:24:55.536084Z","shell.execute_reply.started":"2023-07-30T06:24:55.535869Z","shell.execute_reply":"2023-07-30T06:24:55.535889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.537587Z","iopub.status.idle":"2023-07-30T06:24:55.538017Z","shell.execute_reply.started":"2023-07-30T06:24:55.537819Z","shell.execute_reply":"2023-07-30T06:24:55.537838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.539089Z","iopub.status.idle":"2023-07-30T06:24:55.539487Z","shell.execute_reply.started":"2023-07-30T06:24:55.539294Z","shell.execute_reply":"2023-07-30T06:24:55.539313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.541174Z","iopub.status.idle":"2023-07-30T06:24:55.541573Z","shell.execute_reply.started":"2023-07-30T06:24:55.541376Z","shell.execute_reply":"2023-07-30T06:24:55.541395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_test = test_df.head(18)\nsample_test.head()\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    #img = load_img(\"../input/test1/test1/\"+filename, target_size=IMAGE_SIZE)\n    img = load_img(\"./test1/\"+filename, target_size=IMAGE_SIZE)\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.542857Z","iopub.status.idle":"2023-07-30T06:24:55.544047Z","shell.execute_reply.started":"2023-07-30T06:24:55.543757Z","shell.execute_reply":"2023-07-30T06:24:55.543809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T06:24:55.545497Z","iopub.status.idle":"2023-07-30T06:24:55.546234Z","shell.execute_reply.started":"2023-07-30T06:24:55.546028Z","shell.execute_reply":"2023-07-30T06:24:55.546049Z"},"trusted":true},"execution_count":null,"outputs":[]}]}