{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Main Objective\n\nThe dataset that we will be using, comes from the very popular Dogs vs. Cats Challenge, where our primary objective is to build a deep learning model that can successfully recognize and categorize images into either a cat or a dog.\n\n![](https://miro.medium.com/max/700/1*R-ItxBW2SWarITBKe7HZuA.gif)"},{"metadata":{"trusted":true},"cell_type":"code","source":"!unzip ../input/dogs-vs-cats-redux-kernels-edition/test.zip\n!unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Steps to build Cats vs Dogs classifier:"},{"metadata":{},"cell_type":"markdown","source":"## 1. Import the libraries:"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom keras.preprocessing.image import ImageDataGenerator,load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2. Define image properties:"},{"metadata":{"trusted":true},"cell_type":"code","source":"Image_Width=128\nImage_Height=128\nImage_Size=(Image_Width,Image_Height)\nImage_Channels=3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3. Prepare dataset for training model:"},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames=os.listdir(\"./train\")\ncategories=[]\nfor f_name in filenames:\n    category=f_name.split('.')[0]\n    if category=='dog':\n        categories.append(1)\n    else:\n        categories.append(0)\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":"filenames=os.listdir(\"./test\")\ndf_test=pd.DataFrame({\n    'filename':filenames\n})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4. Create the neural net model:"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Dropout,Flatten,Dense,Activation,BatchNormalization\nmodel=Sequential()\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))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2,activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\noptimizer='rmsprop',metrics=['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 5. Analyzing model:"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6. Define callbacks and learning rate:"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\nearlystop = EarlyStopping(patience = 10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_acc',patience = 2,verbose = 1,factor = 0.5,min_lr = 0.00001)\ncallbacks = [earlystop,learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0:'cat',1:'dog'})\ntrain_df,validate_df = train_test_split(df,test_size=0.20,\n  random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)\ntotal_train=train_df.shape[0]\ntotal_validate=validate_df.shape[0]\nbatch_size=15","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 7. Training and validation data 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                                )\ntrain_generator = train_datagen.flow_from_dataframe(train_df,\n                                                 \"./train\",x_col='filename',y_col='category',\n                                                 target_size=Image_Size,\n                                                 class_mode='categorical',\n                                                 batch_size=batch_size)\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(validate_df, \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                                                            )\ntest_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)\ntest_generator = train_datagen.flow_from_dataframe(df_test,\n                                                 \"./test\",x_col='filename',y_col='category',\n                                                 target_size=Image_Size,\n                                                 class_mode=None,\n                                                 batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 8. Model Training:"},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs=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":"## 9. Save the model:"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"model_10epoch.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 10. Test data preparation:"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filenames = os.listdir(\"./test\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(test_df,nb_samples)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 11. Make categorical prediction:"},{"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":{"trusted":true},"cell_type":"code","source":"predict","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 12. Convert labels to categories:"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\ntest_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 13. Visualize the prediction results:"},{"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(\"./test/\"+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":{"trusted":true},"cell_type":"code","source":"test_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.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}