{"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":"This Kernel for someone want to deep dive into image classification. I use CNN for classification model. If you found this Kernel helpful please up vote it. If you have some feedback and question don't forget to comment below. \n\nI have simplier model with \n* https://www.kaggle.com/uysimty/get-start-image-classification","metadata":{}},{"cell_type":"markdown","source":"# Import Library","metadata":{"_uuid":"fe76d1d1ded592430e7548feacfa38dc42f085d9"}},{"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\nprint(os.listdir(\"../input\"))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-02-11T16:02:14.017633Z","iopub.execute_input":"2023-02-11T16:02:14.017937Z","iopub.status.idle":"2023-02-11T16:02:15.649677Z","shell.execute_reply.started":"2023-02-11T16:02:14.017875Z","shell.execute_reply":"2023-02-11T16:02:15.648769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Constants","metadata":{}},{"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-02-11T16:03:16.622410Z","iopub.execute_input":"2023-02-11T16:03:16.622714Z","iopub.status.idle":"2023-02-11T16:03:16.626949Z","shell.execute_reply.started":"2023-02-11T16:03:16.622655Z","shell.execute_reply":"2023-02-11T16:03:16.626197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare Traning Data","metadata":{"_uuid":"7335a579cc0268fba5d34d6f7558f33c187eedb3"}},{"cell_type":"code","source":"import zipfile\npath_to_zip_file = '../input/test1.zip'\nwith zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:\n    zip_ref.extractall('.')","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:03:19.102857Z","iopub.execute_input":"2023-02-11T16:03:19.103139Z","iopub.status.idle":"2023-02-11T16:03:24.705306Z","shell.execute_reply.started":"2023-02-11T16:03:19.103087Z","shell.execute_reply":"2023-02-11T16:03:24.704308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\npath_to_zip_file = '../input/train.zip'\nwith zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:\n    zip_ref.extractall('.')","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:03:27.239728Z","iopub.execute_input":"2023-02-11T16:03:27.240023Z","iopub.status.idle":"2023-02-11T16:03:38.837996Z","shell.execute_reply.started":"2023-02-11T16:03:27.239963Z","shell.execute_reply":"2023-02-11T16:03:38.836935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"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})","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2023-02-11T16:03:41.462568Z","iopub.execute_input":"2023-02-11T16:03:41.462859Z","iopub.status.idle":"2023-02-11T16:03:41.501622Z","shell.execute_reply.started":"2023-02-11T16:03:41.462802Z","shell.execute_reply":"2023-02-11T16:03:41.500865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"_uuid":"915bb9ba7063ab4d5c07c542419ae119003a5f98","execution":{"iopub.status.busy":"2023-02-11T16:03:43.999432Z","iopub.execute_input":"2023-02-11T16:03:43.999740Z","iopub.status.idle":"2023-02-11T16:03:44.023265Z","shell.execute_reply.started":"2023-02-11T16:03:43.999683Z","shell.execute_reply":"2023-02-11T16:03:44.021985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"_uuid":"72bf69e817f67f5a2eaff8561217e22077248553","execution":{"iopub.status.busy":"2023-02-11T16:03:45.647401Z","iopub.execute_input":"2023-02-11T16:03:45.647821Z","iopub.status.idle":"2023-02-11T16:03:45.660048Z","shell.execute_reply.started":"2023-02-11T16:03:45.647755Z","shell.execute_reply":"2023-02-11T16:03:45.659341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### See Total In count","metadata":{"_uuid":"a999484fc35b73373fafe2253ae9db7ff46fdb90"}},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"_uuid":"fa26f0bc7a6d835a24989790b20f3c6f32946f45","execution":{"iopub.status.busy":"2023-02-11T16:03:47.406807Z","iopub.execute_input":"2023-02-11T16:03:47.407103Z","iopub.status.idle":"2023-02-11T16:03:47.658155Z","shell.execute_reply.started":"2023-02-11T16:03:47.407045Z","shell.execute_reply":"2023-02-11T16:03:47.657158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From our data we have 12000 cats and 12000 dogs","metadata":{"_uuid":"3a08da58107777a1dd05c4a4bf5c484484923cac"}},{"cell_type":"markdown","source":"# See sample image","metadata":{"_uuid":"400a293df3c8499059d9175f3915187074efd971"}},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"train/\"+sample)\nplt.imshow(image)","metadata":{"_uuid":"602b40f7353871cb161c60b5237f0da0096b2f47","execution":{"iopub.status.busy":"2023-02-11T16:03:49.639571Z","iopub.execute_input":"2023-02-11T16:03:49.639860Z","iopub.status.idle":"2023-02-11T16:03:49.991902Z","shell.execute_reply.started":"2023-02-11T16:03:49.639805Z","shell.execute_reply":"2023-02-11T16:03:49.989140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model\n\n<img src=\"https://i.imgur.com/ebkMGGu.jpg\" width=\"100%\"/>","metadata":{"_uuid":"b244e6b7715a04fc6df92dd6dfa3d35c473ca600"}},{"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.\n* **Conv Layer**: This layer will extract features from image.\n* **Pooling Layer**: This layerreduce the spatial volume of input image after convolution.\n* **Fully Connected Layer**: It connect the network from a layer to another layer\n* **Output Layer**: It is the predicted values layer. ","metadata":{}},{"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\n# model.add(Conv2D(32, (3, 3), activation='relu'))\n# model.add(BatchNormalization())\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.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))\n\n# model.add(Dense(128, activation='relu'))\n# model.add(BatchNormalization())\n# model.add(Dropout(0.5))\n\nmodel.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes\n\n#model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"_uuid":"8c9f833c1441b657c779844912d0b8028218d454","execution":{"iopub.status.busy":"2023-02-11T16:03:52.886551Z","iopub.execute_input":"2023-02-11T16:03:52.886831Z","iopub.status.idle":"2023-02-11T16:03:55.706045Z","shell.execute_reply.started":"2023-02-11T16:03:52.886778Z","shell.execute_reply":"2023-02-11T16:03:55.705364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Callbacks","metadata":{"_uuid":"bd496f6c65888a969be3703135b0b03a8a1190c8"}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"_uuid":"9aa032f0f6da539d23918890d2d131cc3aac8c7a","execution":{"iopub.status.busy":"2023-02-11T16:04:01.360202Z","iopub.execute_input":"2023-02-11T16:04:01.360688Z","iopub.status.idle":"2023-02-11T16:04:01.364787Z","shell.execute_reply.started":"2023-02-11T16:04:01.360468Z","shell.execute_reply":"2023-02-11T16:04:01.363807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Early Stop**\n\nTo prevent over fitting we will stop the learning after 10 epochs and val_loss value not decreased","metadata":{"_uuid":"76c9ba4fb7f930c96b2c3e0d6b68ed9fa6a4227b"}},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)","metadata":{"_uuid":"3421c5ec428da6c0d8cc1184179a9caff1e01d1c","execution":{"iopub.status.busy":"2023-02-11T16:04:04.204656Z","iopub.execute_input":"2023-02-11T16:04:04.204939Z","iopub.status.idle":"2023-02-11T16:04:04.209268Z","shell.execute_reply.started":"2023-02-11T16:04:04.204886Z","shell.execute_reply":"2023-02-11T16:04:04.208126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Learning Rate Reduction**\n\nWe will reduce the learning rate when then accuracy not increase for 2 steps","metadata":{"_uuid":"51d3fe52e911286433cedf6e47332948a253361e"}},{"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":{"_uuid":"8010a5661ad8924d2db24af0f3c00b1593b38901","execution":{"iopub.status.busy":"2023-02-11T16:04:06.046859Z","iopub.execute_input":"2023-02-11T16:04:06.047153Z","iopub.status.idle":"2023-02-11T16:04:06.052164Z","shell.execute_reply.started":"2023-02-11T16:04:06.047095Z","shell.execute_reply":"2023-02-11T16:04:06.051406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"_uuid":"a79cc604199469789f183096d863f7248e5f6aab","execution":{"iopub.status.busy":"2023-02-11T16:04:09.716698Z","iopub.execute_input":"2023-02-11T16:04:09.716992Z","iopub.status.idle":"2023-02-11T16:04:09.721985Z","shell.execute_reply.started":"2023-02-11T16:04:09.716936Z","shell.execute_reply":"2023-02-11T16:04:09.721208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{}},{"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) ","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:04:12.695579Z","iopub.execute_input":"2023-02-11T16:04:12.695863Z","iopub.status.idle":"2023-02-11T16:04:12.705068Z","shell.execute_reply.started":"2023-02-11T16:04:12.695809Z","shell.execute_reply":"2023-02-11T16:04:12.704267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"_uuid":"4eeb7af8dcf02c4ef5ca744c8305c51a2f5cedef","execution":{"iopub.status.busy":"2023-02-11T16:04:14.773921Z","iopub.execute_input":"2023-02-11T16:04:14.774238Z","iopub.status.idle":"2023-02-11T16:04:14.785140Z","shell.execute_reply.started":"2023-02-11T16:04:14.774168Z","shell.execute_reply":"2023-02-11T16:04:14.784248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","metadata":{"_uuid":"b84836337441705eda9d2e655665ffa14d9feead","execution":{"iopub.status.busy":"2023-02-11T16:04:16.061560Z","iopub.execute_input":"2023-02-11T16:04:16.061859Z","iopub.status.idle":"2023-02-11T16:04:16.319002Z","shell.execute_reply.started":"2023-02-11T16:04:16.061805Z","shell.execute_reply":"2023-02-11T16:04:16.318021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"_uuid":"19cf03f9a3c39532d6e2d06bd30be49a5afd9d57","execution":{"iopub.status.busy":"2023-02-11T16:04:27.445950Z","iopub.execute_input":"2023-02-11T16:04:27.446402Z","iopub.status.idle":"2023-02-11T16:04:27.679100Z","shell.execute_reply.started":"2023-02-11T16:04:27.446190Z","shell.execute_reply":"2023-02-11T16:04:27.678109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df.sample(10)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:04:29.285963Z","iopub.execute_input":"2023-02-11T16:04:29.286264Z","iopub.status.idle":"2023-02-11T16:04:29.302500Z","shell.execute_reply.started":"2023-02-11T16:04:29.286198Z","shell.execute_reply":"2023-02-11T16:04:29.301774Z"},"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":{"_uuid":"ae3dec0361f0443132d0309d3b883ee80070cf9f","execution":{"iopub.status.busy":"2023-02-11T16:04:31.165990Z","iopub.execute_input":"2023-02-11T16:04:31.166306Z","iopub.status.idle":"2023-02-11T16:04:31.170760Z","shell.execute_reply.started":"2023-02-11T16:04:31.166243Z","shell.execute_reply":"2023-02-11T16:04:31.169696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Traning Generator","metadata":{"_uuid":"ff760be9104f7d9492467b8d9d3405011aa77d11"}},{"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    \"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":{"_uuid":"4d1c7818703a8a4bac5c036fdea45972aa9e5e9e","execution":{"iopub.status.busy":"2023-02-11T16:04:32.975169Z","iopub.execute_input":"2023-02-11T16:04:32.975477Z","iopub.status.idle":"2023-02-11T16:04:33.160340Z","shell.execute_reply.started":"2023-02-11T16:04:32.975415Z","shell.execute_reply":"2023-02-11T16:04:33.159557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Validation Generator","metadata":{"_uuid":"859c7b2857939c19fd2e3bb32839c9f7deb5aa3f"}},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    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)\n","metadata":{"_uuid":"7925e16bcacc89f4484fb6fe47e54d6420af732e","execution":{"iopub.status.busy":"2023-02-11T16:04:34.903520Z","iopub.execute_input":"2023-02-11T16:04:34.904052Z","iopub.status.idle":"2023-02-11T16:04:35.001098Z","shell.execute_reply.started":"2023-02-11T16:04:34.903810Z","shell.execute_reply":"2023-02-11T16:04:35.000375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(validation_generator.class_indices)\nprint(validation_generator.n)\nprint(len(validation_generator))","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:04:36.597318Z","iopub.execute_input":"2023-02-11T16:04:36.597628Z","iopub.status.idle":"2023-02-11T16:04:36.602240Z","shell.execute_reply.started":"2023-02-11T16:04:36.597573Z","shell.execute_reply":"2023-02-11T16:04:36.601461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_val, y_val = validation_generator.__next__()\nprint(X_val.shape, y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:04:38.531273Z","iopub.execute_input":"2023-02-11T16:04:38.531549Z","iopub.status.idle":"2023-02-11T16:04:38.587670Z","shell.execute_reply.started":"2023-02-11T16:04:38.531495Z","shell.execute_reply":"2023-02-11T16:04:38.586897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_list = []\ny_list = []\nfor i in range(validation_generator.__len__()):\n    X, y = validation_generator.__getitem__(i)\n    X_list.append(X)\n    y_list.append(y)\n\nX_val = np.concatenate(X_list, axis=0)\ny_val1 = np.concatenate(y_list, axis=0)\ny_val_argmax = np.argmax(y_val1, axis=1).astype('uint8')","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:04:42.680950Z","iopub.execute_input":"2023-02-11T16:04:42.681250Z","iopub.status.idle":"2023-02-11T16:04:58.235596Z","shell.execute_reply.started":"2023-02-11T16:04:42.681175Z","shell.execute_reply":"2023-02-11T16:04:58.234591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_val.shape, y_val1.shape, y_val_argmax.shape, y_val_argmax[:10]","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:05:01.317789Z","iopub.execute_input":"2023-02-11T16:05:01.318080Z","iopub.status.idle":"2023-02-11T16:05:01.326051Z","shell.execute_reply.started":"2023-02-11T16:05:01.318025Z","shell.execute_reply":"2023-02-11T16:05:01.325320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_list[0].shape","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:05:08.918905Z","iopub.execute_input":"2023-02-11T16:05:08.919192Z","iopub.status.idle":"2023-02-11T16:05:08.924393Z","shell.execute_reply.started":"2023-02-11T16:05:08.919136Z","shell.execute_reply":"2023-02-11T16:05:08.923345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnum_images = 3\n\nrandom_indices = np.random.randint(0, X_val.shape[0], 9)\n\n# Get the images and labels at those indices\nimages = X_val[random_indices]\nlabels = y_val[random_indices]\n\n# Set up the plot with 3 rows and 3 columns\nfig, axs = plt.subplots(3, 3, \n                        figsize=(10,10), \n                        dpi=300)\n\n# Display the images and labels\nfor i in range(3):\n  for j in range(3):\n    axs[i, j].imshow(images[i * 3 + j], cmap='gray')\n    axs[i, j].set_title(f\"Label: {labels[i * 3 + j]}\")\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-02-04T04:45:06.726748Z","iopub.execute_input":"2023-02-04T04:45:06.727177Z","iopub.status.idle":"2023-02-04T04:45:06.803696Z","shell.execute_reply.started":"2023-02-04T04:45:06.726973Z","shell.execute_reply":"2023-02-04T04:45:06.749148Z"}}},{"cell_type":"markdown","source":"# See how our generator work","metadata":{"_uuid":"6e17fc1f002fedd60febb78fee5e81770640b909"}},{"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    \"train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{"_uuid":"4252cce168ab65f88e44a8ebc2672607bc852af4","execution":{"iopub.status.busy":"2023-02-11T16:05:11.197447Z","iopub.execute_input":"2023-02-11T16:05:11.197760Z","iopub.status.idle":"2023-02-11T16:05:11.212879Z","shell.execute_reply.started":"2023-02-11T16:05:11.197706Z","shell.execute_reply":"2023-02-11T16:05:11.211969Z"},"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":{"_uuid":"23d923dba747f8b47dc75569244cecc6f70df321","execution":{"iopub.status.busy":"2023-02-11T16:05:13.189543Z","iopub.execute_input":"2023-02-11T16:05:13.189859Z","iopub.status.idle":"2023-02-11T16:05:15.926100Z","shell.execute_reply.started":"2023-02-11T16:05:13.189802Z","shell.execute_reply":"2023-02-11T16:05:15.925450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Seem to be nice ","metadata":{"_uuid":"810ddf1373d9db470ed48da4f30ca5a6c1274435"}},{"cell_type":"markdown","source":"# Fit Model","metadata":{"_uuid":"5cd8df64e794ed17de326b613a9819e7da977a0e"}},{"cell_type":"code","source":"batch_size","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:05:20.061536Z","iopub.execute_input":"2023-02-11T16:05:20.061915Z","iopub.status.idle":"2023-02-11T16:05:20.068348Z","shell.execute_reply.started":"2023-02-11T16:05:20.061841Z","shell.execute_reply":"2023-02-11T16:05:20.067391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nprint(tf.test.gpu_device_name())","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:05:21.932942Z","iopub.execute_input":"2023-02-11T16:05:21.933247Z","iopub.status.idle":"2023-02-11T16:05:21.939428Z","shell.execute_reply.started":"2023-02-11T16:05:21.933181Z","shell.execute_reply":"2023-02-11T16:05:21.938471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.reset_states()","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:05:23.100737Z","iopub.execute_input":"2023-02-11T16:05:23.101026Z","iopub.status.idle":"2023-02-11T16:05:23.105203Z","shell.execute_reply.started":"2023-02-11T16:05:23.100970Z","shell.execute_reply":"2023-02-11T16:05:23.104043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nepochs=3 if FAST_RUN else 10\nwith tf.device('/device:GPU:0'):\n    history = 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    )","metadata":{"_uuid":"0836a4cc8aa0abf603e0f96573c0c4ff383ad56b","execution":{"iopub.status.busy":"2023-02-11T16:05:24.565837Z","iopub.execute_input":"2023-02-11T16:05:24.566151Z","iopub.status.idle":"2023-02-11T16:33:52.909581Z","shell.execute_reply.started":"2023-02-11T16:05:24.566090Z","shell.execute_reply":"2023-02-11T16:33:52.908360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save Model","metadata":{"_uuid":"aa1fbc4081ae0de2993188b2bf658a0be5bc0687"}},{"cell_type":"code","source":"model.save_weights(\"model.h5\")","metadata":{"_uuid":"67575a4decdaf79a915d23151626b784ffa82642","execution":{"iopub.status.busy":"2023-02-11T16:34:02.516102Z","iopub.execute_input":"2023-02-11T16:34:02.516424Z","iopub.status.idle":"2023-02-11T16:34:02.755482Z","shell.execute_reply.started":"2023-02-11T16:34:02.516367Z","shell.execute_reply":"2023-02-11T16:34:02.754766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Virtualize Training","metadata":{"_uuid":"1b76c0a9040bc0babf0a453e567e41e22f8a1e0e"}},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12), dpi=300)\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['acc'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_acc'], 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()","metadata":{"_uuid":"79055f2dc3e2abb47bea758e0464c86ca42ab431","execution":{"iopub.status.busy":"2023-02-11T16:34:04.890873Z","iopub.execute_input":"2023-02-11T16:34:04.891159Z","iopub.status.idle":"2023-02-11T16:34:08.815322Z","shell.execute_reply.started":"2023-02-11T16:34:04.891104Z","shell.execute_reply":"2023-02-11T16:34:08.814621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare Testing Data","metadata":{"_uuid":"764dc66e4b2bc558f3a0f90b80bb802f5b3d45a8"}},{"cell_type":"code","source":"test_filenames = os.listdir(\"test1/\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"_uuid":"c35e70d3e1e4834dbbf840fa0ea08c049bfcd915","execution":{"iopub.status.busy":"2023-02-11T16:34:13.392995Z","iopub.execute_input":"2023-02-11T16:34:13.393302Z","iopub.status.idle":"2023-02-11T16:34:13.406624Z","shell.execute_reply.started":"2023-02-11T16:34:13.393225Z","shell.execute_reply":"2023-02-11T16:34:13.405741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Testing Generator","metadata":{"_uuid":"291bc3996dce8d05e174b27d64f03996d3e8038e"}},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \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":{"_uuid":"52249ec1c35fb1be3adef386be245de3794e55aa","execution":{"iopub.status.busy":"2023-02-11T16:34:14.899296Z","iopub.execute_input":"2023-02-11T16:34:14.899936Z","iopub.status.idle":"2023-02-11T16:34:15.061430Z","shell.execute_reply.started":"2023-02-11T16:34:14.899877Z","shell.execute_reply":"2023-02-11T16:34:15.060712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Performance model evaluation","metadata":{}},{"cell_type":"code","source":"preds = model.predict_generator(validation_generator, \n                                  steps=total_validate//batch_size + 1,\n                                  verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:17.082152Z","iopub.execute_input":"2023-02-11T16:34:17.082459Z","iopub.status.idle":"2023-02-11T16:34:31.996211Z","shell.execute_reply.started":"2023-02-11T16:34:17.082402Z","shell.execute_reply":"2023-02-11T16:34:31.995064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds.shape","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:34.216772Z","iopub.execute_input":"2023-02-11T16:34:34.217073Z","iopub.status.idle":"2023-02-11T16:34:34.223294Z","shell.execute_reply.started":"2023-02-11T16:34:34.217017Z","shell.execute_reply":"2023-02-11T16:34:34.222148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_val_pred = np.argmax(preds, axis=1)\nprint(y_val_pred.shape)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:35.649591Z","iopub.execute_input":"2023-02-11T16:34:35.649877Z","iopub.status.idle":"2023-02-11T16:34:35.655319Z","shell.execute_reply.started":"2023-02-11T16:34:35.649822Z","shell.execute_reply":"2023-02-11T16:34:35.654356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(y_val_pred), len(y_val_argmax)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:37.664894Z","iopub.execute_input":"2023-02-11T16:34:37.665200Z","iopub.status.idle":"2023-02-11T16:34:37.670556Z","shell.execute_reply.started":"2023-02-11T16:34:37.665141Z","shell.execute_reply":"2023-02-11T16:34:37.669810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_val_pred[:10], y_val_argmax[:10]","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:39.256730Z","iopub.execute_input":"2023-02-11T16:34:39.257024Z","iopub.status.idle":"2023-02-11T16:34:39.265759Z","shell.execute_reply.started":"2023-02-11T16:34:39.256964Z","shell.execute_reply":"2023-02-11T16:34:39.264352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Performance Evaluation","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n#(y_true, y_pred, *, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn')[source]¶\ntarget_names = ['cat', 'dog']\ny_true = y_val_argmax\ny_pred = y_val_pred\n\nprint(classification_report(y_true, y_pred, target_names=target_names))","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:34:40.785773Z","iopub.execute_input":"2023-02-11T16:34:40.786068Z","iopub.status.idle":"2023-02-11T16:34:40.800964Z","shell.execute_reply.started":"2023-02-11T16:34:40.786002Z","shell.execute_reply":"2023-02-11T16:34:40.799977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict","metadata":{"_uuid":"2fa580afca2931ec5ce374e732d8c1789d03f2ed"}},{"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size),\n                                 verbose=1)","metadata":{"_uuid":"4782eb23fa7d003f0e2415d995894017edb2d896","execution":{"iopub.status.busy":"2023-02-11T16:34:42.521672Z","iopub.execute_input":"2023-02-11T16:34:42.521962Z","iopub.status.idle":"2023-02-11T16:35:30.058924Z","shell.execute_reply.started":"2023-02-11T16:34:42.521908Z","shell.execute_reply":"2023-02-11T16:35:30.055371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{}},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:35:41.808726Z","iopub.execute_input":"2023-02-11T16:35:41.809018Z","iopub.status.idle":"2023-02-11T16:35:41.813419Z","shell.execute_reply.started":"2023-02-11T16:35:41.808964Z","shell.execute_reply":"2023-02-11T16:35:41.812646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{}},{"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-02-11T16:35:43.599907Z","iopub.execute_input":"2023-02-11T16:35:43.600198Z","iopub.status.idle":"2023-02-11T16:35:43.608621Z","shell.execute_reply.started":"2023-02-11T16:35:43.600143Z","shell.execute_reply":"2023-02-11T16:35:43.606399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{}},{"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"execution":{"iopub.status.busy":"2023-02-11T16:35:45.223955Z","iopub.execute_input":"2023-02-11T16:35:45.224256Z","iopub.status.idle":"2023-02-11T16:35:45.234045Z","shell.execute_reply.started":"2023-02-11T16:35:45.224185Z","shell.execute_reply":"2023-02-11T16:35:45.233315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Virtaulize Result","metadata":{"_uuid":"b00add65fe765529e637c3a9904d710bb7eff1d8"}},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{"_uuid":"d0bf6dd5ff344092fa0121f70bdd60fa5a40e29c","execution":{"iopub.status.busy":"2023-02-11T16:35:48.857702Z","iopub.execute_input":"2023-02-11T16:35:48.858029Z","iopub.status.idle":"2023-02-11T16:35:49.177589Z","shell.execute_reply.started":"2023-02-11T16:35:48.857977Z","shell.execute_reply":"2023-02-11T16:35:49.176863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### See predicted result with images","metadata":{"_uuid":"ce72a83f80d6e012b12b82c8ee3365d671a3b307"}},{"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(\"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":{"_uuid":"98b41dc83075e6297137fb45bf703c313dd4ae28","execution":{"iopub.status.busy":"2023-02-11T16:35:50.943778Z","iopub.execute_input":"2023-02-11T16:35:50.944060Z","iopub.status.idle":"2023-02-11T16:35:55.301846Z","shell.execute_reply.started":"2023-02-11T16:35:50.944007Z","shell.execute_reply":"2023-02-11T16:35:55.301215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{"_uuid":"d1ca25943e73aa20a37f9fb8670ee430caeaaf1f"}},{"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":{"_uuid":"cce9f3e2ffff0693d79d84590ed71fbbca7c3c7c","execution":{"iopub.status.busy":"2023-02-11T16:35:59.239944Z","iopub.execute_input":"2023-02-11T16:35:59.240264Z","iopub.status.idle":"2023-02-11T16:35:59.469336Z","shell.execute_reply.started":"2023-02-11T16:35:59.240185Z","shell.execute_reply":"2023-02-11T16:35:59.468340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}