{"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":"code","source":"import os\nimport cv2\nimport random\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.preprocessing import MultiLabelBinarizer","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-24T06:55:22.052154Z","iopub.execute_input":"2021-11-24T06:55:22.053182Z","iopub.status.idle":"2021-11-24T06:55:29.028890Z","shell.execute_reply.started":"2021-11-24T06:55:22.053093Z","shell.execute_reply":"2021-11-24T06:55:29.027613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"HEIGHT = 480\nWIDTH = 480\nCHANNELS = 3\nCLASSES = 6\ntop_dropout_rate = 0.2","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:55:39.283070Z","iopub.execute_input":"2021-11-24T06:55:39.283434Z","iopub.status.idle":"2021-11-24T06:55:39.289121Z","shell.execute_reply.started":"2021-11-24T06:55:39.283394Z","shell.execute_reply":"2021-11-24T06:55:39.287851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weights_path = \"../input/efnet-v2-insectaug-model/EfficientNet_V2_InsectAug.h5\"\nhub_url = '../input/efficientnetv2-tfhub-weight-files/tfhub_models/efficientnetv2-l-21k-ft1k/feature_vector'","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:55:43.311494Z","iopub.execute_input":"2021-11-24T06:55:43.311998Z","iopub.status.idle":"2021-11-24T06:55:43.316229Z","shell.execute_reply.started":"2021-11-24T06:55:43.311956Z","shell.execute_reply":"2021-11-24T06:55:43.315323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model():\n    model = tf.keras.Sequential([\n            tf.keras.layers.InputLayer(input_shape = [HEIGHT, WIDTH, CHANNELS]),\n            hub.KerasLayer(hub_url, trainable = True),\n            Dropout(top_dropout_rate, name = \"top_dropout\"),\n            Dense(CLASSES, activation = 'sigmoid')\n        ])\n    model.build((HEIGHT, WIDTH, CHANNELS))\n    model.compile(optimizer ='adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n    model.summary()\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:55:45.355012Z","iopub.execute_input":"2021-11-24T06:55:45.355935Z","iopub.status.idle":"2021-11-24T06:55:45.363949Z","shell.execute_reply.started":"2021-11-24T06:55:45.355882Z","shell.execute_reply":"2021-11-24T06:55:45.362820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = get_model()\nmodel.load_weights(weights_path)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:55:48.112016Z","iopub.execute_input":"2021-11-24T06:55:48.112303Z","iopub.status.idle":"2021-11-24T06:56:40.295848Z","shell.execute_reply.started":"2021-11-24T06:55:48.112274Z","shell.execute_reply":"2021-11-24T06:56:40.294960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_img = '../input/plant-pathology-2021-fgvc8/test_images'\nsubmission = pd.read_csv('../input/plant-pathology-2021-fgvc8/sample_submission.csv')\nsubmission","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:56:52.805488Z","iopub.execute_input":"2021-11-24T06:56:52.806403Z","iopub.status.idle":"2021-11-24T06:56:52.825880Z","shell.execute_reply.started":"2021-11-24T06:56:52.806364Z","shell.execute_reply":"2021-11-24T06:56:52.824868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_image(image_id):\n    file_path = str(image_id)\n    img = cv2.imread(test_img+'/'+file_path)\n    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:56:55.614119Z","iopub.execute_input":"2021-11-24T06:56:55.614527Z","iopub.status.idle":"2021-11-24T06:56:55.627449Z","shell.execute_reply.started":"2021-11-24T06:56:55.614455Z","shell.execute_reply":"2021-11-24T06:56:55.626087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def insect_augmentation(image, n_insects = 2, dark_insect=False, p = 0.5, insects_folder='../input/insect/insect'):\n    aug_prob = random.random()\n    flag = False\n    if aug_prob < p:\n        flag = True\n        height, width, _ = image.shape  # target image width and height\n        insects_images = os.listdir(insects_folder)\n        img_shape = image.shape\n\n        for _ in range(n_insects):\n            insect = cv2.cvtColor(cv2.imread(os.path.join(insects_folder, random.choice(insects_images))), cv2.COLOR_RGB2BGR)\n            insect = cv2.flip(insect, random.choice([-1, 0, 1]))\n            insect = cv2.rotate(insect, random.choice([0, 1, 2]))\n            insect = cv2.resize(insect, (width, height))\n\n            h_height, h_width, _ = insect.shape  # insect image width and height\n            roi_ho = random.randint(0, image.shape[0] - insect.shape[0])\n            roi_wo = random.randint(0, image.shape[1] - insect.shape[1])\n            roi = image[roi_ho:roi_ho + h_height, roi_wo:roi_wo + h_width]\n\n            # Creating a mask and inverse mask \n            img2gray = cv2.cvtColor(insect, cv2.COLOR_BGR2GRAY)\n            ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)\n            #mask_inv = cv2.cvtColor(cv2.bitwise_not(mask),cv2.COLOR_BGR2GRAY)\n            mask_inv = cv2.bitwise_not(mask)\n\n            # Now black-out the area of insect in ROI\n            img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n            # Take only region of insect from insect image.\n            if dark_insect:\n                img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n                insect_fg = cv2.bitwise_and(img_bg, img_bg, mask=mask)\n            else:\n                insect_fg = cv2.bitwise_and(insect, insect, mask=mask)\n\n            # Put insect in ROI and modify the target image\n            dst = cv2.add(img_bg, insect_fg, dtype = cv2.CV_64F)\n\n            image[roi_ho:roi_ho + h_height, roi_wo:roi_wo + h_width] = dst\n\n\n    return image","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:56:58.260828Z","iopub.execute_input":"2021-11-24T06:56:58.261325Z","iopub.status.idle":"2021-11-24T06:56:58.278292Z","shell.execute_reply.started":"2021-11-24T06:56:58.261293Z","shell.execute_reply":"2021-11-24T06:56:58.276780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process(img):\n    img = insect_augmentation(img, n_insects = random.randint(1, 2), dark_insect=False, p = 0.2)\n    img = tf.cast(img, tf.float32) / 255.0\n    img = np.array(img)\n    return cv2.resize(img , (480, 480)).reshape(-1, 480, 480, 3)\ndef predict(img):\n    img = load_image(img)\n    tta_steps = 5\n    predictions = []\n    for i in range(tta_steps):\n        pred = model.layers[2](model.layers[1](model.layers[0](process(img)))).numpy()[0]\n        predictions.append(pred)\n    result = np.median(predictions, axis=0)\n    \n    return result","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:57:03.062293Z","iopub.execute_input":"2021-11-24T06:57:03.063135Z","iopub.status.idle":"2021-11-24T06:57:03.074650Z","shell.execute_reply.started":"2021-11-24T06:57:03.063083Z","shell.execute_reply":"2021-11-24T06:57:03.073538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_images = submission['image'][0]\ntest_images = load_image(test_images)\npreds = model.layers[2](model.layers[1](model.layers[0](process(test_images)))).numpy()[0]\nprint(preds)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:57:05.974796Z","iopub.execute_input":"2021-11-24T06:57:05.975336Z","iopub.status.idle":"2021-11-24T06:57:17.138075Z","shell.execute_reply.started":"2021-11-24T06:57:05.975305Z","shell.execute_reply":"2021-11-24T06:57:17.136989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_label = ['complex', 'frog_eye_leaf_spot', 'healthy', 'powdery_mildew', 'rust', 'scab']\nlabel = []\nfor i in range(len(submission['image'])):\n    test_images = submission['image'][i]\n    preds = predict(test_images)\n    answer = []\n    for j in range(len(preds)):\n        if preds[j] > 0.2:\n            answer.append(n_label[j])\n    answer = ' '.join(answer)\n    label.append(answer)\nsubmission['labels'] = label\nsubmission","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:58:03.687792Z","iopub.execute_input":"2021-11-24T06:58:03.688208Z","iopub.status.idle":"2021-11-24T06:58:09.949936Z","shell.execute_reply.started":"2021-11-24T06:58:03.688176Z","shell.execute_reply":"2021-11-24T06:58:09.949010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T06:58:27.449034Z","iopub.execute_input":"2021-11-24T06:58:27.449333Z","iopub.status.idle":"2021-11-24T06:58:27.459649Z","shell.execute_reply.started":"2021-11-24T06:58:27.449302Z","shell.execute_reply":"2021-11-24T06:58:27.458374Z"},"trusted":true},"execution_count":null,"outputs":[]}]}