{"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":"markdown","source":"\n\n# Import libraries.\n","metadata":{"id":"zqrYqv734KAo"}},{"cell_type":"code","source":"# Core\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport glob\nimport random\nimport os\nimport cv2\n#tesor fow & keras\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.regularizers import l2     \nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.models import load_model\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense,BatchNormalization,Dropout,Input\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D,GlobalMaxPooling2D\nfrom tensorflow.keras.applications import  Xception,VGG16,InceptionResNetV2\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n#cnn\nfrom tensorflow.keras import datasets, layers, models\n\nfrom keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda\nfrom keras.engine.base_layer import Layer\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score","metadata":{"id":"1eb99db7","execution":{"iopub.status.busy":"2022-02-27T18:39:38.214963Z","iopub.execute_input":"2022-02-27T18:39:38.215309Z","iopub.status.idle":"2022-02-27T18:39:44.458440Z","shell.execute_reply.started":"2022-02-27T18:39:38.215229Z","shell.execute_reply":"2022-02-27T18:39:44.457767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed = 42\nnp.random.seed =seed","metadata":{"id":"4DTeuvL_TphS","execution":{"iopub.status.busy":"2022-02-26T11:21:35.305141Z","iopub.execute_input":"2022-02-26T11:21:35.305341Z","iopub.status.idle":"2022-02-26T11:21:35.308879Z","shell.execute_reply.started":"2022-02-26T11:21:35.305317Z","shell.execute_reply":"2022-02-26T11:21:35.308253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Exetract  Files","metadata":{}},{"cell_type":"code","source":"import zipfile\n\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2022-02-26T11:21:54.915204Z","iopub.execute_input":"2022-02-26T11:21:54.915767Z","iopub.status.idle":"2022-02-26T11:22:11.319419Z","shell.execute_reply.started":"2022-02-26T11:21:54.915727Z","shell.execute_reply":"2022-02-26T11:22:11.318655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_path = '/kaggle/working'","metadata":{"id":"qcaudVrD0uQ2","execution":{"iopub.status.busy":"2022-02-26T11:22:14.962613Z","iopub.execute_input":"2022-02-26T11:22:14.963475Z","iopub.status.idle":"2022-02-26T11:22:14.96784Z","shell.execute_reply.started":"2022-02-26T11:22:14.96341Z","shell.execute_reply":"2022-02-26T11:22:14.966493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Bussiness Task\n\nIn this competition, you'll write an algorithm to classify whether images contain either a dog or a cat.  This is easy for humans, dogs, and cats. Your computer will find it a bit more difficult.\n\n**I hope you find this NoteBook helpful and some <span style=\"color:red;\">UPVOTES</span> would be appreciated.**\n  \n\n","metadata":{"id":"JE_1ztaHWq4h"}},{"cell_type":"markdown","source":"# Helper Function\n\n\n","metadata":{"id":"2zDVR6bc8DyI"}},{"cell_type":"code","source":"#this function used to get code simple\n\n# get label Name   \ndef get_Label(number):\n    labels = {0:'Cat', 1:'Dog'}\n    return labels[number]\n\n\n#plot predction function\ndef plot_predection(model_name):\n    plt.figure(figsize=(20,15))\n    plt.suptitle(\"Predection  Images\", fontsize=20)\n    images = [] \n    path =image_path+'/'+'test1/'\n    count = 0  #val_images,val_labels\n    for i,files in enumerate(os.listdir(path)) :\n        img = plt.imread(path+files)\n        img = cv2.resize(img,(128,128))\n        plt.imshow(img,cmap=plt.cm.binary)\n        img = np.expand_dims(img, axis=0)\n        feature = model_name.predict(img)\n        predection  = np.argmax(feature, axis=1)\n        plt.subplot(5,7,i+1)\n        plt.xticks([])\n        plt.yticks([])\n        plt.grid(False)\n        plt.xlabel(\"Predicted\"+get_Label(int(predection)))\n        count += 1\n        if count == 34 :\n            break                ","metadata":{"id":"veeEUr6oElre","execution":{"iopub.status.busy":"2022-02-26T13:29:21.234866Z","iopub.execute_input":"2022-02-26T13:29:21.23515Z","iopub.status.idle":"2022-02-26T13:29:21.243947Z","shell.execute_reply.started":"2022-02-26T13:29:21.235121Z","shell.execute_reply":"2022-02-26T13:29:21.243191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n# Data Preperation \nLoad Labels\n*   collect all image label and add it in data frame.\n\nLoad Images\n*   Train images\n*   Test images\n*   Validation images\n\n","metadata":{"id":"5ssSyiLDdTlP"}},{"cell_type":"code","source":"# 0 for cat ,1 for dog\nall_categories = []\nimages = os.listdir(image_path+'/'+'train')\nfor file in images:\n    if file.split('.')[0] == 'dog':\n        all_categories.append(1)\n    else:\n        all_categories.append(0)\n#creat data fram to save each image with its label \ndf =pd.DataFrame({\n    'image': images,\n    'category':all_categories\n})\n\ndf.head(5)","metadata":{"id":"t5Acfd4xik4n","outputId":"d7014f41-eca0-41da-b840-a3c81f6ee027","execution":{"iopub.status.busy":"2022-02-26T11:22:20.191926Z","iopub.execute_input":"2022-02-26T11:22:20.192477Z","iopub.status.idle":"2022-02-26T11:22:20.246813Z","shell.execute_reply.started":"2022-02-26T11:22:20.192417Z","shell.execute_reply":"2022-02-26T11:22:20.24603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts()","metadata":{"id":"jT6svNwoq6cA","outputId":"cf363dbf-f182-448f-b6a0-7ecb67eddb1b","execution":{"iopub.status.busy":"2022-02-26T11:22:22.805502Z","iopub.execute_input":"2022-02-26T11:22:22.806202Z","iopub.status.idle":"2022-02-26T11:22:22.845655Z","shell.execute_reply.started":"2022-02-26T11:22:22.806156Z","shell.execute_reply":"2022-02-26T11:22:22.844788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Virsialization Train Images ","metadata":{"id":"GADSmKVF6ODR"}},{"cell_type":"code","source":"plt.title('Train Labels Visualization')\nsns.countplot(x=all_categories,palette='flare')\nplt.show()","metadata":{"id":"QleRc-rlqUP8","outputId":"14ebe6b4-6575-4e67-8c06-0c3a1111e391","execution":{"iopub.status.busy":"2022-02-26T11:22:24.065896Z","iopub.execute_input":"2022-02-26T11:22:24.066148Z","iopub.status.idle":"2022-02-26T11:22:24.295996Z","shell.execute_reply.started":"2022-02-26T11:22:24.06612Z","shell.execute_reply":"2022-02-26T11:22:24.2953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n*   Frome Here We Find Data is Totaly Balanced.\n\n","metadata":{"id":"925RC9Aa8IVj"}},{"cell_type":"code","source":"plt.figure(figsize=(20,15))\nplt.suptitle(\"Train Images\", fontsize=20)\npath =image_path+'/'+'train/'\ncounter =0\nfor i,img in enumerate(os.listdir(path))  :\n        plt.subplot(5,7,i+1)\n        full_image= plt.imread(path+img)\n        plt.xticks([])\n        plt.yticks([])\n        plt.grid(False)\n        plt.xlabel(get_Label(all_categories[i]))\n        plt.imshow(full_image, cmap=plt.cm.binary) \n        if i == 34:\n            break","metadata":{"id":"fOLq0LLW6SQj","outputId":"2fc737ac-2f79-4f62-d765-ea4cca7458fb","execution":{"iopub.status.busy":"2022-02-26T11:22:24.634228Z","iopub.execute_input":"2022-02-26T11:22:24.634702Z","iopub.status.idle":"2022-02-26T11:22:27.221025Z","shell.execute_reply.started":"2022-02-26T11:22:24.634662Z","shell.execute_reply":"2022-02-26T11:22:27.220274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#conver label to categorical in stead of numerical value to use feature of image generator \ndf['category'] = df['category'].replace({1:'dog',0:'cat'})\ndf.head(10)","metadata":{"id":"cFOAeJjJilJf","outputId":"42e58118-4fd2-441a-d9e2-b25f4dc83c03","execution":{"iopub.status.busy":"2022-02-26T11:22:27.557385Z","iopub.execute_input":"2022-02-26T11:22:27.557657Z","iopub.status.idle":"2022-02-26T11:22:27.569003Z","shell.execute_reply.started":"2022-02-26T11:22:27.557629Z","shell.execute_reply":"2022-02-26T11:22:27.568352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts()","metadata":{"id":"p8_mmSOf3KAP","outputId":"94386a88-e5b2-4b17-d498-df8182925a55","execution":{"iopub.status.busy":"2022-02-26T11:22:35.229601Z","iopub.execute_input":"2022-02-26T11:22:35.230277Z","iopub.status.idle":"2022-02-26T11:22:35.239274Z","shell.execute_reply.started":"2022-02-26T11:22:35.230239Z","shell.execute_reply":"2022-02-26T11:22:35.238596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preperation\n\n\n1.   Data speliting\n2.   re index to spleated data to order data \n3.   get shape of data\n\n","metadata":{"id":"-bhO4m2YC4Xn"}},{"cell_type":"code","source":"#splid data to train and test\nx_train,x_val  = train_test_split(df ,random_state=42,shuffle=True,test_size=0.2)","metadata":{"id":"e946tm3GCNen","execution":{"iopub.status.busy":"2022-02-26T11:22:40.941115Z","iopub.execute_input":"2022-02-26T11:22:40.941371Z","iopub.status.idle":"2022-02-26T11:22:40.951065Z","shell.execute_reply.started":"2022-02-26T11:22:40.941342Z","shell.execute_reply":"2022-02-26T11:22:40.950216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train['category'].value_counts()","metadata":{"id":"ahR6A37-1HAv","outputId":"f077eac8-a80b-4f67-ece8-b8f32d3f4836","execution":{"iopub.status.busy":"2022-02-26T11:22:41.717633Z","iopub.execute_input":"2022-02-26T11:22:41.718119Z","iopub.status.idle":"2022-02-26T11:22:41.727819Z","shell.execute_reply.started":"2022-02-26T11:22:41.718082Z","shell.execute_reply":"2022-02-26T11:22:41.727171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_val['category'].value_counts()","metadata":{"id":"f9L60UTy1dM8","outputId":"852b27c7-b8d2-4f99-c747-bba79ad92729","execution":{"iopub.status.busy":"2022-02-26T11:22:43.702243Z","iopub.execute_input":"2022-02-26T11:22:43.702772Z","iopub.status.idle":"2022-02-26T11:22:43.710768Z","shell.execute_reply.started":"2022-02-26T11:22:43.702733Z","shell.execute_reply":"2022-02-26T11:22:43.710057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# reindex Data Frame\nx_train = x_train.reset_index(drop=True)\nx_val = x_val.reset_index(drop=True)\n","metadata":{"id":"qWRoiifREOE6","execution":{"iopub.status.busy":"2022-02-26T11:22:43.893522Z","iopub.execute_input":"2022-02-26T11:22:43.893906Z","iopub.status.idle":"2022-02-26T11:22:43.899045Z","shell.execute_reply.started":"2022-02-26T11:22:43.893872Z","shell.execute_reply":"2022-02-26T11:22:43.898387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Train Images shape is        : ',x_train.shape)\nprint('Validation  Images  shape is : ',x_val.shape)","metadata":{"id":"zOAeW-MggSdQ","outputId":"2bd462b6-83b4-4fba-d944-1ba3399c84ca","execution":{"iopub.status.busy":"2022-02-26T11:22:44.098207Z","iopub.execute_input":"2022-02-26T11:22:44.098982Z","iopub.status.idle":"2022-02-26T11:22:44.106906Z","shell.execute_reply.started":"2022-02-26T11:22:44.098925Z","shell.execute_reply":"2022-02-26T11:22:44.105787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Buliding CNN Model\n\n**i will use Data augmentation,as it  is a set of techniques to artificially increase the amount of data by generating new data points from existing data. This includes making small changes to data or using deep learning models to generate new data points.** \n\n","metadata":{"id":"5O1NZpjrijnM"}},{"cell_type":"code","source":"batch_size = 64\n#create image generator for images \nimage_gen = ImageDataGenerator(\n                                 rescale = 1./255,\n                                  shear_range = 0.2,\n                                  zoom_range = 0.5,\n                                  height_shift_range=0.2,\n                                  width_shift_range=0.2,\n                                  fill_mode='nearest',\n                                   horizontal_flip=True,\n                                   rotation_range = 20, \n                            \n                               )\n\n# Create Image Data Generator for Test/Validation Set\ntest_data_gen = ImageDataGenerator(  \n                                   rescale = 1./255,\n                                  shear_range = 0.2,\n                                  zoom_range = 0.5,\n                                  height_shift_range=0.2,\n                                  width_shift_range=0.2,\n                                  fill_mode='nearest',\n                                   horizontal_flip=True,\n                                   rotation_range = 20,)\n\n        \ntrain = image_gen.flow_from_dataframe(\n      x_train,\n      image_path+'/'+'train/',\n      x_col='image',\n      y_col='category',\n      target_size=(128,128),\n      class_mode='categorical',\n      shuffle=True, \n      batch_size=batch_size\n      )\nvalidate = test_data_gen.flow_from_dataframe(\n      x_val,\n      image_path+'/'+'train/',\n      x_col='image',\n      y_col='category',\n      target_size=(128,128),\n      class_mode='categorical',\n      shuffle=True, \n      batch_size=batch_size\n      )\n","metadata":{"id":"p7jQbFP742OG","outputId":"42dbe29c-86fa-421c-d95f-b9dc34852c21","execution":{"iopub.status.busy":"2022-02-26T11:22:46.808864Z","iopub.execute_input":"2022-02-26T11:22:46.809391Z","iopub.status.idle":"2022-02-26T11:22:47.069903Z","shell.execute_reply.started":"2022-02-26T11:22:46.809353Z","shell.execute_reply":"2022-02-26T11:22:47.06833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get shape of train data \nfor train_img , train_label in train :\n    print('image shape ',train_img.shape)\n    print('label  shape ',train_label.shape)\n    break ","metadata":{"id":"OCLV-gLvLE5z","outputId":"c5fa5cd0-ece9-4c94-d933-3fd55c423194","execution":{"iopub.status.busy":"2022-02-26T11:22:49.348355Z","iopub.execute_input":"2022-02-26T11:22:49.348803Z","iopub.status.idle":"2022-02-26T11:22:49.701677Z","shell.execute_reply.started":"2022-02-26T11:22:49.348768Z","shell.execute_reply":"2022-02-26T11:22:49.700939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get shape of train data \nfor v_img , v_label in validate :\n    print('image shape ',v_img.shape)\n    print('label  shape ',v_label.shape)\n    break ","metadata":{"id":"wN3Oz9z1LdhH","outputId":"a30217ca-b06f-45f6-c6b3-55c8a653751f","execution":{"iopub.status.busy":"2022-02-26T11:22:49.703214Z","iopub.execute_input":"2022-02-26T11:22:49.703636Z","iopub.status.idle":"2022-02-26T11:22:50.047893Z","shell.execute_reply.started":"2022-02-26T11:22:49.703596Z","shell.execute_reply":"2022-02-26T11:22:50.047121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#start bulding CNN Model\ncnn_model = Sequential()\ncnn_model = models.Sequential()\ncnn_model.add(layers.Conv2D(64,(3,3),padding ='Same',activation = 'relu',input_shape=(128,128,3)))\ncnn_model.add(layers.MaxPooling2D(2,2))\ncnn_model.add(layers.Conv2D(64,(3,3) ,padding ='same',activation='relu'))\ncnn_model.add(layers.MaxPooling2D(2,2))\ncnn_model.add(layers.Conv2D(128,(3,3),padding ='same',activation='relu'))\ncnn_model.add(layers.MaxPooling2D(2,2)) \ncnn_model.add(layers.Conv2D(128,(3,3) ,padding ='same',activation='relu'))\ncnn_model.add(layers.MaxPooling2D(2,2)) \ncnn_model.add(layers.Conv2D(256,(3,3) ,padding ='same',activation='relu'))\ncnn_model.add(layers.MaxPooling2D(2,2)) \ncnn_model.add(BatchNormalization())\ncnn_model.add(layers.Conv2D(256,(3,3) ,padding ='same',activation='relu'))\ncnn_model.add(layers.MaxPooling2D(2,2)) \ncnn_model.add(BatchNormalization())\ncnn_model.summary()\n# cnn_model.add(Dropout(0.2))\n","metadata":{"id":"QfsDiDZE42Qz","outputId":"17e7b3d0-b9dc-458a-a5fa-ec1e50f2dd64","execution":{"iopub.status.busy":"2022-02-26T11:22:51.905784Z","iopub.execute_input":"2022-02-26T11:22:51.906174Z","iopub.status.idle":"2022-02-26T11:22:54.409892Z","shell.execute_reply.started":"2022-02-26T11:22:51.906139Z","shell.execute_reply":"2022-02-26T11:22:54.409119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn_model.add(layers.Flatten())\ncnn_model.add(layers.Dense(1024, activation='relu'))\ncnn_model.add(BatchNormalization())\n# cnn_model.add(Dropout(0.7))\ncnn_model.add(layers.Dense(512, activation='relu'))\ncnn_model.add(BatchNormalization())\n# cnn_model.add(Dropout(0.3))\ncnn_model.add(layers.Dense(2, activation ='softmax'))\ncnn_model.summary()","metadata":{"id":"S92wdti_cHH6","outputId":"3fc54a1f-2fb0-4309-d9a2-8fdbbc8b5bc2","execution":{"iopub.status.busy":"2022-02-26T11:23:00.964137Z","iopub.execute_input":"2022-02-26T11:23:00.964389Z","iopub.status.idle":"2022-02-26T11:23:01.033927Z","shell.execute_reply.started":"2022-02-26T11:23:00.96436Z","shell.execute_reply":"2022-02-26T11:23:01.033245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn_model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'],)","metadata":{"id":"EMoCr59t42Td","execution":{"iopub.status.busy":"2022-02-26T11:23:04.994829Z","iopub.execute_input":"2022-02-26T11:23:04.995382Z","iopub.status.idle":"2022-02-26T11:23:05.010286Z","shell.execute_reply.started":"2022-02-26T11:23:04.995344Z","shell.execute_reply":"2022-02-26T11:23:05.009492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  **1-Defining Callbacks**\n\n*   A callback is an object that can perform actions at various stages of training (e.g. at the start or end of an epoch, before or after a single batch, etc)\n\n\n**2-Reduce Learning Rate on Plateau**\n*   Is used to reduce the learning rate when a metric has stopped improving.\n\n","metadata":{"id":"ubaCfhsU_6QF"}},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping,ReduceLROnPlateau\nearly = EarlyStopping(monitor=\"loss\", mode=\"min\",min_delta = 0,\n                          patience = 10,\n                          verbose = 1,\n                          restore_best_weights = True)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='loss', patience = 2, verbose=1,factor=0.3, min_lr=0.000001)\ncallbacks_list = [ early, learning_rate_reduction]","metadata":{"id":"uxLfTTyhFnFy","execution":{"iopub.status.busy":"2022-02-26T11:23:07.892318Z","iopub.execute_input":"2022-02-26T11:23:07.893103Z","iopub.status.idle":"2022-02-26T11:23:07.898989Z","shell.execute_reply.started":"2022-02-26T11:23:07.893058Z","shell.execute_reply":"2022-02-26T11:23:07.898303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training model\nn_training_samples = len(train)\nn_validation_samples = len(validate)\nhistory = cnn_model.fit(\n    train,\n    epochs=60,\n    validation_data=validate,\n    validation_steps=n_validation_samples//batch_size,\n    # steps_per_epoch =n_training_samples//batch_size,\n    shuffle = True,\n    callbacks=callbacks_list\n    )","metadata":{"id":"CKSuE6FQ42WE","outputId":"a1c6e07b-52aa-4dce-df90-f21c8f199c9b","execution":{"iopub.status.busy":"2022-02-26T11:23:11.838415Z","iopub.execute_input":"2022-02-26T11:23:11.839098Z","iopub.status.idle":"2022-02-26T13:22:03.6512Z","shell.execute_reply.started":"2022-02-26T11:23:11.83906Z","shell.execute_reply":"2022-02-26T13:22:03.650478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score, acc = cnn_model.evaluate(validate,batch_size=batch_size)                       \nprint('Test score:', score)\nprint('Test accuracy:', acc)","metadata":{"id":"iqieAIee42Yy","outputId":"77175719-3974-4005-dd36-95caa0fcf615","execution":{"iopub.status.busy":"2022-02-26T13:31:39.383996Z","iopub.execute_input":"2022-02-26T13:31:39.384679Z","iopub.status.idle":"2022-02-26T13:32:09.368984Z","shell.execute_reply.started":"2022-02-26T13:31:39.384641Z","shell.execute_reply":"2022-02-26T13:32:09.36812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn_prediction = cnn_model.predict(validate)\ncnn_prediction","metadata":{"id":"yroCkc8e42eQ","outputId":"4bd20a96-f915-4cc2-c667-6c55a7a49c8c","execution":{"iopub.status.busy":"2022-02-26T13:32:15.896603Z","iopub.execute_input":"2022-02-26T13:32:15.897184Z","iopub.status.idle":"2022-02-26T13:32:45.488917Z","shell.execute_reply.started":"2022-02-26T13:32:15.897147Z","shell.execute_reply":"2022-02-26T13:32:45.488243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.5, 1])\nplt.legend(loc='lower right')\nplt.show()","metadata":{"id":"5gWhTl-3PJK0","outputId":"c2d59fca-8942-4b6e-abad-25a41917abd7","execution":{"iopub.status.busy":"2022-02-26T13:32:45.490515Z","iopub.execute_input":"2022-02-26T13:32:45.491115Z","iopub.status.idle":"2022-02-26T13:32:45.676165Z","shell.execute_reply.started":"2022-02-26T13:32:45.491077Z","shell.execute_reply":"2022-02-26T13:32:45.675497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# prepare data for predection.\n\n\n\n\n","metadata":{"id":"Jv77PJTFAlzg"}},{"cell_type":"code","source":"#get image path\ntest_images = os.listdir(image_path+'/'+'test1')\n\n#creat data frame\ndf_test =pd.DataFrame({\n    'image': test_images,\n})\n\ndf_test.head()\n\n#prepare generator\nval_data_gen  = ImageDataGenerator( rescale = 1./255, )  \n        \ntesting = val_data_gen.flow_from_dataframe(\n      df_test,\n      image_path+'/'+'test1/',\n      x_col='image',\n      y_col= None,\n      target_size=(128,128),\n      class_mode=None,\n      shuffle=True, \n      batch_size=batch_size\n      )\n","metadata":{"id":"pU24REUsWsot","outputId":"43292598-c1ff-4f98-80b1-196f24442438","execution":{"iopub.status.busy":"2022-02-26T13:33:11.26712Z","iopub.execute_input":"2022-02-26T13:33:11.26739Z","iopub.status.idle":"2022-02-26T13:33:11.382685Z","shell.execute_reply.started":"2022-02-26T13:33:11.267362Z","shell.execute_reply":"2022-02-26T13:33:11.381962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predction Using CNN.","metadata":{"id":"LE7e42i4Wi6l"}},{"cell_type":"code","source":"predection = cnn_model.predict(testing)\npredection","metadata":{"id":"bM9aQDSKUdKJ","outputId":"55525d69-6679-404b-9cda-b7d558c0c0b0","execution":{"iopub.status.busy":"2022-02-26T13:23:59.321254Z","iopub.execute_input":"2022-02-26T13:23:59.321573Z","iopub.status.idle":"2022-02-26T13:24:30.258957Z","shell.execute_reply.started":"2022-02-26T13:23:59.32153Z","shell.execute_reply":"2022-02-26T13:24:30.25824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.argmax(predection,axis=1)[0:100]","metadata":{"id":"KzCxJToEPcnq","outputId":"cbd66454-108a-4fb8-cebe-d552faa9e079","execution":{"iopub.status.busy":"2022-02-26T13:24:30.260466Z","iopub.execute_input":"2022-02-26T13:24:30.260876Z","iopub.status.idle":"2022-02-26T13:24:30.268347Z","shell.execute_reply.started":"2022-02-26T13:24:30.260836Z","shell.execute_reply":"2022-02-26T13:24:30.2675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_predection(cnn_model)","metadata":{"id":"0IxBfBZ-MPp3","outputId":"0d9102ed-6a30-47c1-a0b8-514b08e273a5","execution":{"iopub.status.busy":"2022-02-26T13:33:19.622953Z","iopub.execute_input":"2022-02-26T13:33:19.62321Z","iopub.status.idle":"2022-02-26T13:33:23.367721Z","shell.execute_reply.started":"2022-02-26T13:33:19.623183Z","shell.execute_reply":"2022-02-26T13:33:23.367063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Thanks for  <span style=\"color:red;\">Reviewing</span> My kernel also, if you have any comments or suggestion please raise it**","metadata":{}}]}