{"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. ","metadata":{}},{"cell_type":"markdown","source":"# Import Libraries","metadata":{"_uuid":"fe76d1d1ded592430e7548feacfa38dc42f085d9"}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd \n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.utils import to_categorical\n\nimport matplotlib.pyplot as plt\nimport random\n\nprint(os.listdir(\"../input\"))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-01-31T12:11:45.437194Z","iopub.execute_input":"2022-01-31T12:11:45.437506Z","iopub.status.idle":"2022-01-31T12:11:46.449431Z","shell.execute_reply.started":"2022-01-31T12:11:45.437444Z","shell.execute_reply":"2022-01-31T12:11:46.447153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Constants","metadata":{}},{"cell_type":"code","source":"# True if you want to quick test you model (training for 3 epochs). False to have a full train (50 epochs).\nFAST_RUN = False \nepochs = 3 if FAST_RUN else 50\n# Enter the width and height of images.\nIMAGE_WIDTH=256\nIMAGE_HEIGHT=192\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\n# 3 if RGB. 1 if Grayscale.\nIMAGE_CHANNELS=3\nbatch_size = 32\n# Dropout rate\nd = 0.3\n\n# Use when training on pre-trained weights\nSTART_EPOCH = 0 # if fresh train, enter 0\nTransfer = False\nPretrained_Link = \"../input/pretrained-model/model.h5\"","metadata":{"execution":{"iopub.status.busy":"2022-01-31T12:11:46.451208Z","iopub.execute_input":"2022-01-31T12:11:46.451538Z","iopub.status.idle":"2022-01-31T12:11:46.459815Z","shell.execute_reply.started":"2022-01-31T12:11:46.451478Z","shell.execute_reply":"2022-01-31T12:11:46.458453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training Preparation: Loading Images and Labels","metadata":{"_uuid":"7335a579cc0268fba5d34d6f7558f33c187eedb3"}},{"cell_type":"code","source":"# Create a blank dataframe with two columns: image file name and the waste category\ndf = pd.DataFrame({\n    'filename': [],\n    'category': []\n})\n\ndirectory = \"../input/unsortedwaste/UnSortedWaste/\"\n# directory of images\nfilenames = os.listdir(directory)\n\n# append filename and category of all images into the dataframe, one by one.\nfor filename in filenames:\n        # use the first three letters of image file name to identify category.\n        category = filename[0:3]\n        if category == 'car':\n            categories='cardboard'\n        elif category == 'gla':\n            categories='glass'\n        elif category == 'met':\n            categories='metal'\n        elif category == 'pap':\n            categories='paper'\n        elif category == 'pla':\n            categories='plastic'\n        else:\n            categories='trash'\n        df=df.append({'filename':directory + filename, 'category': categories},ignore_index=True)\n\n# load from another dataset ---------------------------------------------------------------------\ndirectory = \"../input/waste-images-2/solid_waste/\"\n# directory of images\nfilenames = os.listdir(directory)\n\n# append filename and category of all images into the dataframe, one by one.\nfor filename in filenames:\n        # use the first three letters of image file name to identify category.\n        category = filename[0:3]\n        if category == 'car':\n            categories='cardboard'\n        elif category == 'gla':\n            categories='glass'\n        elif category == 'met':\n            categories='metal'\n        elif category == 'pap':\n            categories='paper'\n        elif category == 'pla':\n            categories='plastic'\n        else:\n            categories='trash'\n        df=df.append({'filename':directory + filename, 'category': categories},ignore_index=True)\n","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2022-01-31T12:11:46.461924Z","iopub.execute_input":"2022-01-31T12:11:46.462759Z","iopub.status.idle":"2022-01-31T12:12:01.374058Z","shell.execute_reply.started":"2022-01-31T12:11:46.462696Z","shell.execute_reply":"2022-01-31T12:12:01.373206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.dropna()\nprint(\"Number of images = {}\".format(df.size))\n# Quick look of the dataframe\ndf.head()","metadata":{"_uuid":"72bf69e817f67f5a2eaff8561217e22077248553","execution":{"iopub.status.busy":"2022-01-31T12:12:01.375653Z","iopub.execute_input":"2022-01-31T12:12:01.376016Z","iopub.status.idle":"2022-01-31T12:12:01.421638Z","shell.execute_reply.started":"2022-01-31T12:12:01.375958Z","shell.execute_reply":"2022-01-31T12:12:01.420415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Overview of data","metadata":{"_uuid":"a999484fc35b73373fafe2253ae9db7ff46fdb90"}},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()\nprint (df['category'].value_counts())","metadata":{"_uuid":"fa26f0bc7a6d835a24989790b20f3c6f32946f45","execution":{"iopub.status.busy":"2022-01-31T12:12:01.424051Z","iopub.execute_input":"2022-01-31T12:12:01.424648Z","iopub.status.idle":"2022-01-31T12:12:01.756163Z","shell.execute_reply.started":"2022-01-31T12:12:01.424378Z","shell.execute_reply":"2022-01-31T12:12:01.754895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From our data we have 2167 glass, 2123 plastic, 2085 metal, 594 paper, 403 cardboards, and 137 trash.","metadata":{"_uuid":"3a08da58107777a1dd05c4a4bf5c484484923cac"}},{"cell_type":"markdown","source":"# Training Preparation: Splitting Training and Testing","metadata":{}},{"cell_type":"code","source":"# Randomly sample 80% of data from dataframe for training. Replace = False to prevent repeat sampling.\ndf_train=df.sample(frac=0.8,replace=False)\n# The rest 20% is the validation images.\ndf_valid=df.drop(df_train.index.values)","metadata":{"execution":{"iopub.status.busy":"2022-01-31T12:12:01.757982Z","iopub.execute_input":"2022-01-31T12:12:01.758434Z","iopub.status.idle":"2022-01-31T12:12:01.777137Z","shell.execute_reply.started":"2022-01-31T12:12:01.758360Z","shell.execute_reply":"2022-01-31T12:12:01.775790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Overview of training dataset","metadata":{}},{"cell_type":"code","source":"df_train['category'].value_counts().plot.bar()\nprint (df_train['category'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2022-01-31T12:12:01.782503Z","iopub.execute_input":"2022-01-31T12:12:01.785536Z","iopub.status.idle":"2022-01-31T12:12:02.127629Z","shell.execute_reply.started":"2022-01-31T12:12:01.785466Z","shell.execute_reply":"2022-01-31T12:12:02.126546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Overview of testing dataset","metadata":{}},{"cell_type":"code","source":"df_valid['category'].value_counts().plot.bar()\nprint(df_valid['category'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2022-01-31T12:12:02.132843Z","iopub.execute_input":"2022-01-31T12:12:02.135833Z","iopub.status.idle":"2022-01-31T12:12:02.568457Z","shell.execute_reply.started":"2022-01-31T12:12:02.135748Z","shell.execute_reply":"2022-01-31T12:12:02.565201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### See sample image","metadata":{"_uuid":"400a293df3c8499059d9175f3915187074efd971"}},{"cell_type":"code","source":"sample = random.choice(df_train['filename'])\nimage = load_img(sample)\nplt.imshow(image)\nprint(sample)","metadata":{"_uuid":"602b40f7353871cb161c60b5237f0da0096b2f47","execution":{"iopub.status.busy":"2022-01-31T12:12:02.571142Z","iopub.execute_input":"2022-01-31T12:12:02.571477Z","iopub.status.idle":"2022-01-31T12:12:03.191759Z","shell.execute_reply.started":"2022-01-31T12:12:02.571419Z","shell.execute_reply":"2022-01-31T12:12:03.190878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Looking good! Now we can start building our model.","metadata":{}},{"cell_type":"markdown","source":"# Build Model","metadata":{"_uuid":"b244e6b7715a04fc6df92dd6dfa3d35c473ca600"}},{"cell_type":"markdown","source":"Use Keras Sequential to build model to extract 2D visual values.","metadata":{}},{"cell_type":"code","source":"# Importing models from Keras\nfrom tensorflow.keras.models import Sequential\n# Import from \"tensorflow.keras.layers\" instead of \"tensorflow.keras\" \n# so that we don't need to write \"layers.\" in every line\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, BatchNormalization\n# Create Keras Sequential Model\nmodel = Sequential([\n        # Convolution 2D layer (filters, strides, activation function, padding) \n        Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)),\n        # Normalize to inprove accuracy\n        BatchNormalization(),\n        # Extract features, reduce image size\n        MaxPooling2D(pool_size=(2, 2)),\n        # Dropout to prevent overfitting\n        Dropout(d),\n\n        Conv2D(64, (3, 3), activation='relu',padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(pool_size=(2, 2)),\n        Dropout(d),\n\n        Conv2D(128, (3, 3), activation='relu',padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(pool_size=(2, 2)),\n        Dropout(d),\n    \n        Conv2D(256, (3, 3), activation='relu',padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(pool_size=(2, 2)),\n        Dropout(d),\n\n        # Flatten 3D tensor (2D visual + 1D channel) into 1D array to pass through Dense layer\n        Flatten(),\n        Dense(1024, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.5),\n        Dense(512, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.5),\n        Dense(128, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.5),\n        Dense(6, activation='softmax')# 6 because we have 6 classes\n])\n\nif Transfer:\n    model.load_weights(Pretrained_Link)\n\nmodel.compile(\n    # use categorical\n    loss='categorical_crossentropy', \n    optimizer='adam', \n    metrics=['categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"_uuid":"8c9f833c1441b657c779844912d0b8028218d454","execution":{"iopub.status.busy":"2022-01-31T12:12:03.196613Z","iopub.execute_input":"2022-01-31T12:12:03.199145Z","iopub.status.idle":"2022-01-31T12:12:04.436186Z","shell.execute_reply.started":"2022-01-31T12:12:03.199067Z","shell.execute_reply":"2022-01-31T12:12:04.435021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Callbacks","metadata":{"_uuid":"bd496f6c65888a969be3703135b0b03a8a1190c8"}},{"cell_type":"code","source":"# import needed libraries\nfrom tensorflow.keras.callbacks import EarlyStopping, LearningRateScheduler","metadata":{"_uuid":"9aa032f0f6da539d23918890d2d131cc3aac8c7a","execution":{"iopub.status.busy":"2022-01-31T12:12:04.439580Z","iopub.execute_input":"2022-01-31T12:12:04.439894Z","iopub.status.idle":"2022-01-31T12:12:04.458060Z","shell.execute_reply.started":"2022-01-31T12:12:04.439823Z","shell.execute_reply":"2022-01-31T12:12:04.455771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Early Stop\n\nTo prevent overfitting, we will stop training if the validation dataset accuracy doesn't increase for 10 consecutive epochs. Then we will restore the best weights throughout the training.","metadata":{"_uuid":"76c9ba4fb7f930c96b2c3e0d6b68ed9fa6a4227b"}},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=10,restore_best_weights=True)","metadata":{"_uuid":"3421c5ec428da6c0d8cc1184179a9caff1e01d1c","execution":{"iopub.status.busy":"2022-01-31T12:12:04.459437Z","iopub.execute_input":"2022-01-31T12:12:04.459738Z","iopub.status.idle":"2022-01-31T12:12:04.467861Z","shell.execute_reply.started":"2022-01-31T12:12:04.459683Z","shell.execute_reply":"2022-01-31T12:12:04.466758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Learning Rate Scheduler\n\nReduce the Learning Rate over time to increase training accuracy over time.\n\nThis is like switching from the rough calibration on a microscope to the fine calibration","metadata":{"_uuid":"51d3fe52e911286433cedf6e47332948a253361e"}},{"cell_type":"code","source":"# Learning rate (LR) schedule for TPU, GPU and CPU.\n\nLR_START = 5e-4\nLR_MIN = 1e-6\nLR_EXP_DECAY = .94\n\n# Define a Learning Rate function on epoch that will decrease exponentially.\ndef lrfn(epoch):\n    lr = (LR_START - LR_MIN) * LR_EXP_DECAY**(epoch+START_EPOCH) + LR_MIN\n    return lr\n    \nlr_callback = LearningRateScheduler(lrfn, verbose=True)\n\n# Visualize the change in learning rate\nrng = [i for i in range(START_EPOCH,epochs+START_EPOCH)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g}\".format(y[0], y[-1]))","metadata":{"execution":{"iopub.status.busy":"2022-01-31T12:12:04.469595Z","iopub.execute_input":"2022-01-31T12:12:04.469968Z","iopub.status.idle":"2022-01-31T12:12:04.781328Z","shell.execute_reply.started":"2022-01-31T12:12:04.469905Z","shell.execute_reply":"2022-01-31T12:12:04.779982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare data","metadata":{}},{"cell_type":"markdown","source":"### Overview of all data","metadata":{}},{"cell_type":"code","source":"# Total number of images for training\ntotal_train = df_train.shape[0]\n# Total number of images for validation\ntotal_validate = df_valid.shape[0]\n\nprint(\"Training: {}, Validation: {}\".format(total_train,total_validate))","metadata":{"_uuid":"ae3dec0361f0443132d0309d3b883ee80070cf9f","execution":{"iopub.status.busy":"2022-01-31T12:12:04.787121Z","iopub.execute_input":"2022-01-31T12:12:04.787774Z","iopub.status.idle":"2022-01-31T12:12:04.800983Z","shell.execute_reply.started":"2022-01-31T12:12:04.787493Z","shell.execute_reply":"2022-01-31T12:12:04.799322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training Image Generator for model fitting","metadata":{"_uuid":"ff760be9104f7d9492467b8d9d3405011aa77d11"}},{"cell_type":"code","source":"# Use tensorflow.keras.preprocessing.image.ImageDataGenerator for data Augmentation\n# Stretch, rotate, rescale, flip, etc. the training waste images to better train the model\ntrain_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\n# According to the dataframe, pull images one by one from image directory\ntrain_generator = train_datagen.flow_from_dataframe(\n    df_train, \n    \"\", \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":"2022-01-31T12:12:04.802754Z","iopub.execute_input":"2022-01-31T12:12:04.803489Z","iopub.status.idle":"2022-01-31T12:12:16.339262Z","shell.execute_reply.started":"2022-01-31T12:12:04.803076Z","shell.execute_reply":"2022-01-31T12:12:16.337917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Validation Generator","metadata":{"_uuid":"859c7b2857939c19fd2e3bb32839c9f7deb5aa3f"}},{"cell_type":"code","source":"# Validation doesn't need much data Augmentation\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\n\n# According to the dataframe, pull images one by one from image directory\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    df_valid, \n    \"\", \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":"7925e16bcacc89f4484fb6fe47e54d6420af732e","execution":{"iopub.status.busy":"2022-01-31T12:12:16.341176Z","iopub.execute_input":"2022-01-31T12:12:16.341619Z","iopub.status.idle":"2022-01-31T12:12:18.947365Z","shell.execute_reply.started":"2022-01-31T12:12:16.341519Z","shell.execute_reply":"2022-01-31T12:12:18.946288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test functionality of generators","metadata":{"_uuid":"6e17fc1f002fedd60febb78fee5e81770640b909"}},{"cell_type":"code","source":"# Get one sample image name from train dataframe\nexample_df = df_train.sample(n=1).reset_index(drop=True)\n# Pull the image from directory\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)\n\n# Plot the effect of the data augmentation\nplt.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()\n\nexample_df","metadata":{"_uuid":"4252cce168ab65f88e44a8ebc2672607bc852af4","execution":{"iopub.status.busy":"2022-01-31T12:12:18.948869Z","iopub.execute_input":"2022-01-31T12:12:18.949213Z","iopub.status.idle":"2022-01-31T12:12:22.154304Z","shell.execute_reply.started":"2022-01-31T12:12:18.949154Z","shell.execute_reply":"2022-01-31T12:12:22.153244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Seems nice!","metadata":{"_uuid":"810ddf1373d9db470ed48da4f30ca5a6c1274435"}},{"cell_type":"markdown","source":"# Fit Model","metadata":{"_uuid":"5cd8df64e794ed17de326b613a9819e7da977a0e"}},{"cell_type":"code","source":"history = model.fit(\n    # The train generator just tested, can pull training images out from directory.\n    train_generator, \n    # Batch size and epochs already set at beginning.\n    batch_size=batch_size,\n    epochs=epochs,\n    # The validation generator, can pull validation images out from directory.\n    validation_data=validation_generator,\n\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    # Two callback methods: early stopping and learning rate scheduling\n    callbacks=[earlystop, lr_callback]\n)\n\n# Save Model\nmodel.save_weights(\"model.h5\")","metadata":{"_uuid":"0836a4cc8aa0abf603e0f96573c0c4ff383ad56b","execution":{"iopub.status.busy":"2022-01-31T12:12:22.156002Z","iopub.execute_input":"2022-01-31T12:12:22.156648Z","iopub.status.idle":"2022-01-31T13:11:11.264132Z","shell.execute_reply.started":"2022-01-31T12:12:22.156572Z","shell.execute_reply":"2022-01-31T13:11:11.262828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualize Training","metadata":{"_uuid":"1b76c0a9040bc0babf0a453e567e41e22f8a1e0e"}},{"cell_type":"code","source":"import matplotlib.pyplot as plt \nimport matplotlib\n# Visualize the training process by graphing the loss curves and accuracy curves\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\n\nax1.plot(history.history['loss'],c=\"b\",label=\"Training loss\")\nax1.plot(history.history['val_loss'], c='r', label=\"validation loss\")\nax1.legend()\nax1.grid()\nax1.set_xticks(np.arange(1, len(history.history[\"loss\"]), 5))\nax1.set_yticks(np.arange(0, max(history.history['val_loss']), round(max(history.history['val_loss'])/10, 1)))\n\nax2.plot(history.history['categorical_accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_categorical_accuracy'], color='r',label=\"Validation accuracy\")\nax2.legend()\nax2.grid()\nax2.set_xticks(np.arange(1, len(history.history[\"loss\"]), 5))\nax2.set_yticks(np.arange(0, 1, 0.05))\nplt.tight_layout()\nplt.show()","metadata":{"_uuid":"79055f2dc3e2abb47bea758e0464c86ca42ab431","execution":{"iopub.status.busy":"2022-01-31T13:27:47.712310Z","iopub.execute_input":"2022-01-31T13:27:47.712636Z","iopub.status.idle":"2022-01-31T13:27:48.708179Z","shell.execute_reply.started":"2022-01-31T13:27:47.712575Z","shell.execute_reply":"2022-01-31T13:27:48.706271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare Testing Data","metadata":{"_uuid":"764dc66e4b2bc558f3a0f90b80bb802f5b3d45a8"}},{"cell_type":"code","source":"# Since this notebook is not in a competition, \n# we will just randomly select samples from the dataset for testing.\n# Randomly select 30% of data\ntest_df = df.sample(frac = 0.3)\n# Number of testing samples\nnb_samples = test_df.shape[0]","metadata":{"_uuid":"c35e70d3e1e4834dbbf840fa0ea08c049bfcd915","execution":{"iopub.status.busy":"2022-01-31T13:21:24.360537Z","iopub.execute_input":"2022-01-31T13:21:24.360862Z","iopub.status.idle":"2022-01-31T13:21:24.371519Z","shell.execute_reply.started":"2022-01-31T13:21:24.360801Z","shell.execute_reply":"2022-01-31T13:21:24.370563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Testing Generator","metadata":{"_uuid":"291bc3996dce8d05e174b27d64f03996d3e8038e"}},{"cell_type":"code","source":"# Test generator in the same fashion of the train/validation generators\ntest_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"\", \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":"2022-01-31T13:21:25.649309Z","iopub.execute_input":"2022-01-31T13:21:25.649676Z","iopub.status.idle":"2022-01-31T13:21:26.548175Z","shell.execute_reply.started":"2022-01-31T13:21:25.649614Z","shell.execute_reply":"2022-01-31T13:21:26.546918Z"},"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))","metadata":{"_uuid":"4782eb23fa7d003f0e2415d995894017edb2d896","execution":{"iopub.status.busy":"2022-01-31T13:21:30.370848Z","iopub.execute_input":"2022-01-31T13:21:30.371273Z","iopub.status.idle":"2022-01-31T13:21:40.052398Z","shell.execute_reply.started":"2022-01-31T13:21:30.371166Z","shell.execute_reply":"2022-01-31T13:21:40.051072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# For categoral classication the prediction will come with probability of each category. \n# So we will pick the category that have the highest probability with numpy average max\n# We store the predicted results besides the true labels in a dataframe.\ntest_df['pred_category'] = np.argmax(predict, axis=-1)\n\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['pred_category'] = test_df['pred_category'].replace(label_map)","metadata":{"execution":{"iopub.status.busy":"2022-01-31T13:21:40.054061Z","iopub.execute_input":"2022-01-31T13:21:40.054452Z","iopub.status.idle":"2022-01-31T13:21:40.071200Z","shell.execute_reply.started":"2022-01-31T13:21:40.054393Z","shell.execute_reply":"2022-01-31T13:21:40.067984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Visualize Result","metadata":{"_uuid":"b00add65fe765529e637c3a9904d710bb7eff1d8"}},{"cell_type":"code","source":"test_df['pred_category'].value_counts().plot.bar()","metadata":{"_uuid":"d0bf6dd5ff344092fa0121f70bdd60fa5a40e29c","execution":{"iopub.status.busy":"2022-01-31T13:21:43.078740Z","iopub.execute_input":"2022-01-31T13:21:43.079162Z","iopub.status.idle":"2022-01-31T13:21:43.426428Z","shell.execute_reply.started":"2022-01-31T13:21:43.079013Z","shell.execute_reply":"2022-01-31T13:21:43.425267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### See predicted result with images","metadata":{"_uuid":"ce72a83f80d6e012b12b82c8ee3365d671a3b307"}},{"cell_type":"code","source":"import matplotlib.pyplot as plt \nimport matplotlib\n\nsample_test = test_df.sample(n=18)\nplt.figure(figsize=(12, 24))\n\ni=1\nfor index, row in sample_test.iterrows():\n    if i <= 18:\n        filename = row['filename']\n        category = row['pred_category']\n        img = load_img(filename, target_size=IMAGE_SIZE)\n        plt.subplot(6, 3, i)\n        plt.imshow(img)\n        plt.title('(predicted=' + \"{}\".format(category) + ')')\n        i+=1\nplt.tight_layout()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-31T13:22:48.049994Z","iopub.execute_input":"2022-01-31T13:22:48.050371Z","iopub.status.idle":"2022-01-31T13:22:53.221230Z","shell.execute_reply.started":"2022-01-31T13:22:48.050309Z","shell.execute_reply":"2022-01-31T13:22:53.220266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df.to_csv('./submission.csv', index=False)\ntest_df.head(30)","metadata":{"_uuid":"cce9f3e2ffff0693d79d84590ed71fbbca7c3c7c","execution":{"iopub.status.busy":"2022-01-31T13:28:51.381002Z","iopub.execute_input":"2022-01-31T13:28:51.381449Z","iopub.status.idle":"2022-01-31T13:28:51.421515Z","shell.execute_reply.started":"2022-01-31T13:28:51.381374Z","shell.execute_reply":"2022-01-31T13:28:51.420552Z"},"trusted":true},"execution_count":null,"outputs":[]}]}