{"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":{},"cell_type":"markdown","source":"Importing the Required Libraries"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nimport tensorflow as tf\nimport zipfile\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Define Constants"},{"metadata":{"trusted":true},"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare Traning Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"def extract_files(source_path, target_path):\n    zip_ref = zipfile.ZipFile(source_path,'r')\n    zip_ref.extractall(target_path)\n    zip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"extract_files('/kaggle/input/dogs-vs-cats/test1.zip','/kaggle/working/')\nextract_files('/kaggle/input/dogs-vs-cats/train.zip','/kaggle/working/')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir(\"/kaggle/working/train\")\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})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.tail()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"See Total In count"},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"See sample image"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"/kaggle/working/train/\"+sample)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Build Model"},{"metadata":{},"cell_type":"markdown","source":"Input Layer: It represent input image data. It will reshape image into single diminsion array. Example your image is 64x64 = 4096, it will convert to (4096,1) array.\nConv Layer: This layer will extract features from image.\nPooling Layer: This layerreduce the spatial volume of input image after convolution.\nFully Connected Layer: It connect the network from a layer to another layer\nOutput Layer: It is the predicted values layer."},{"metadata":{"trusted":true},"cell_type":"code","source":"model = 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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Early Stop"},{"metadata":{},"cell_type":"markdown","source":"To prevent over fitting we will stop the learning after 10 epochs and val_loss value not decreased"},{"metadata":{"trusted":true},"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Learning Rate Reduction"},{"metadata":{},"cell_type":"markdown","source":"We will reduce the learning rate when then accuracy not increase for 2 steps"},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare data"},{"metadata":{},"cell_type":"markdown","source":"Because we will use image genaretor with class_mode=\"categorical\". We need to convert column category into string. Then imagenerator will convert it one-hot encoding which is good for our classification.\n\nSo we will convert 1 to dog and 0 to cat"},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Traning Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(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    \"/kaggle/working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Validation Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"/kaggle/working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"See how our generator work"},{"metadata":{"trusted":true},"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    \"/kaggle/working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Fit Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs=3 if FAST_RUN else 10\nhistory = model.fit_generator(\n    train_generator, \n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Save Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Visualize Training"},{"metadata":{"trusted":true},"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))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare Testing Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filenames = os.listdir(\"/kaggle/working/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Create Testing Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"/kaggle/working/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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For categoral classication the prediction will come with probability of each category. So we will pick the category that have the highest probability with numpy average max\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We will convert the predict category back into our generator classes by using train_generator.class_indices. It is the classes that image generator map while converting data into computer vision"},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From our prepare data part. We map data with {1: 'dog', 0: 'cat'}. Now we will map the result back to dog is 1 and cat is 0"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Virtaulize Result"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"See predicted result with images"},{"metadata":{"trusted":true},"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(\"/kaggle/working/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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Submission File Generation"},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare Traning Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir(\"/kaggle/working/train\")\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})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"See Total In count"},{"metadata":{},"cell_type":"markdown","source":"'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"resnet_weights_path = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D\n\nnum_classes = 2\nresnet_weights_path = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\n\nmy_new_model = Sequential()\nmy_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path))\nmy_new_model.add(Dense(num_classes, activation='softmax'))\n\n# Indicate whether the first layer should be trained/changed or not.\nmy_new_model.layers[0].trainable = False\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Compile the Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"my_new_model.compile(optimizer='sgd', \n                     loss='categorical_crossentropy', \n                     metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Fit Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls images/train/upright","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img\nimg = load_img('images/kaggle/input/dogs-vs-cats/train.zip')\nimg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img\nimg = load_img('/kaggle/input/dogs-vs-cats/test1.zip')\nimg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\n\nimage_size = 224\ndata_generator = ImageDataGenerator(preprocess_input)\n\ntrain_generator = data_generator.flow_from_directory(\n                                        directory='images/train',\n                                        target_size=(image_size, image_size),\n                                        batch_size=10,\n                                        class_mode='categorical')\n\n\n\nvalidation_generator = data_generator.flow_from_directory(\n                                        directory='images/val',\n                                        target_size=(image_size, image_size),\n                                        class_mode='categorical')\n\n\n\n# fit_stats below saves some statistics describing how model fitting went\n# the key role of the following line is how it changes my_new_model by fitting to data\nfit_stats = my_new_model.fit_generator(train_generator,\n                                       epochs=2,\n                                       steps_per_epoch=22,\n                                       validation_data=validation_generator,\n                                       validation_steps=1)\n\n#step_4.check()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = validation_generator.filenames\nnb_samples = len(filenames)\n\npredict = my_new_model.predict_generator(validation_generator,steps = nb_samples)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\npred = np.argmax(predict, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,accuracy_score\nconfusion_matrix(pred,test_generator.labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy_score(pred,test_generator.labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\n\nimage_size = 224\ndata_generator = ImageDataGenerator(preprocess_input)\n\ntrain_generator = data_generator.flow_from_directory(\n                                        directory='images/train',\n                                        target_size=(image_size, image_size),\n                                        batch_size=10,\n                                        class_mode='categorical')\n\n\n\nvalidation_generator = data_generator.flow_from_directory(\n                                        directory='images/val',\n                                        target_size=(image_size, image_size),\n                                        class_mode='categorical')\n\n\n\n# fit_stats below saves some statistics describing how model fitting went\n# the key role of the following line is how it changes my_new_model by fitting to data\nfit_stats = my_new_model.fit_generator(train_generator,\n                                       epochs=2,\n                                       steps_per_epoch=22,\n                                       validation_data=validation_generator,\n                                       validation_steps=1)\n\n#step_4.check()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Data Augumentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.python.keras.preprocessing.image import ImageDataGenerator\ndata_generator_with_aug = ImageDataGenerator(preprocessing_function=preprocess_input,\n                                   horizontal_flip=True,\n                                   width_shift_range = 0.2,\n                                   height_shift_range = 0.2)\n\ntrain_generator_aug = data_generator_with_aug.flow_from_directory(\n        'images/train',\n        target_size=(image_size, image_size),\n        batch_size=24,\n        class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = validation_generator.filenames\nnb_samples = len(filenames)\n\npredict = my_new_model.predict_generator(validation_generator,steps = nb_samples)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_generator_no_aug = ImageDataGenerator(preprocessing_function=preprocess_input)\nvalidation_generator_no_aug = data_generator_no_aug.flow_from_directory(\n        'images/val',\n        target_size=(image_size, image_size),\n        class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fit_stats = my_new_model.fit_generator(train_generator_aug,\n                                       epochs=2,\n                                       steps_per_epoch=22,\n                                       validation_data=validation_generator_no_aug,\n                                       validation_steps=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(preprocess_input)\n\ntest_generator = test_datagen.flow_from_directory(\n        'images/val',\n        target_size=(image_size, image_size),\n        color_mode=\"rgb\",\n        shuffle = False,\n        class_mode='categorical',\n        batch_size=1)\n\nfilenames = test_generator.filenames\nnb_samples = len(filenames)\n\npredict = my_new_model.predict_generator(test_generator,steps = nb_samples)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\npred = np.argmax(predict, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,accuracy_score\nconfusion_matrix(pred,test_generator.labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy_score(pred,test_generator.labels)","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}