{"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":"!pip install tez\n!pip install efficientnet-pytorch","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport albumentations\nimport pandas as pd\nimport numpy as np\n\nimport tez\nfrom tez.datasets import ImageDataset\nfrom tez.callbacks import EarlyStopping\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom efficientnet_pytorch import EfficientNet\nfrom sklearn import metrics, model_selection, preprocessing","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"# model\nclass LeafModel(tez.Model):\n    def __init__(self, num_classes):\n        super().__init__()\n        \n        self.effnet = EfficientNet.from_pretrained(\"efficientnet-b4\")\n        self.dropout = nn.Dropout(0.1)\n        self.out = nn.Linear(1792, num_classes)\n        self.step_scheduler_after = \"epoch\"\n        \n    def monitor_metrics(self, outputs, targets):\n        if targets is None:\n            return {}\n        outputs = torch.argmax(outputs, dim=1).cpu().detach().numpy()\n        targets = targets.cpu().detach().numpy()\n        acc = metrics.accuracy_score(targets, outputs)\n        return {\n            \"accuracy\": acc\n        }\n        \n    def fetch_optimizer(self):\n        opt = torch.optim.Adam(self.parameters(), lr=3e-4)\n        return opt\n    \n    def fetch_scheduler(self):\n        sch = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=0.7)\n        return sch\n    \n    def forward(self, image, targets=None):\n        batch_size = image.shape[0]\n        \n        x = self.effnet.extract_features(image)\n        x = F.adaptive_avg_pool2d(x, 1).reshape(batch_size, -1)\n        outputs = self.out(self.dropout(x))\n        \n        if targets is not None:\n            loss = nn.CrossEntropyLoss()(outputs, targets)\n            metrics = self.monitor_metrics(outputs, targets)\n            return outputs, loss, metrics\n        return outputs, None, None\n        ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Augmentations","metadata":{}},{"cell_type":"code","source":"# augmentations taken from: https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-train-amp-aug\ntrain_aug = albumentations.Compose([\n            albumentations.RandomResizedCrop(256, 256),\n            albumentations.Transpose(p=0.5),\n            albumentations.HorizontalFlip(p=0.5),\n            albumentations.VerticalFlip(p=0.5),\n            albumentations.ShiftScaleRotate(p=0.5),\n            albumentations.HueSaturationValue(\n                hue_shift_limit=0.2, \n                sat_shift_limit=0.2, \n                val_shift_limit=0.2, \n                p=0.5\n            ),\n            albumentations.RandomBrightnessContrast(\n                brightness_limit=(-0.1,0.1), \n                contrast_limit=(-0.1, 0.1), \n                p=0.5\n            ),\n            albumentations.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            ),\n            albumentations.CoarseDropout(p=0.5),\n            albumentations.Cutout(p=0.5)], p=1.)\n  \n        \nvalid_aug = albumentations.Compose([\n            albumentations.CenterCrop(256, 256, p=1.),\n            albumentations.Resize(256, 256),\n            albumentations.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            )], p=1.)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")\ndf_train, df_valid = model_selection.train_test_split(df, test_size=0.1,\n                                                     random_state=42, stratify=df.label.values)\n\ndf_train = df_train.reset_index(drop=True)\ndf_valid = df_train.reset_index(drop=True)\n\n\nimage_path = \"../input/cassava-leaf-disease-classification/train_images/\"\ntrain_image_paths = [os.path.join(image_path, x) for x in df_train.image_id.values]\nvalid_image_paths = [os.path.join(image_path, x) for x in df_valid.image_id.values]\n\ntrain_targets = df_train.label.values\nvalid_targets = df_valid.label.values\n\ntrain_dataset = ImageDataset(\n    image_paths = train_image_paths,\n    targets = train_targets,\n    augmentations = train_aug\n)\n\nvalid_dataset = ImageDataset(\n    image_paths = valid_image_paths,\n    targets = valid_targets,\n    augmentations = valid_aug\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","metadata":{}},{"cell_type":"code","source":"model = LeafModel(num_classes=df.label.nunique())\nes = EarlyStopping(\n    monitor=\"valid_loss\",\n    model_path=\"model.bin\",\n    patience=3,\n    mode=\"min\"\n)\n\nmodel.fit(\n    train_dataset,\n    valid_dataset=valid_dataset,\n    train_bs = 64,\n    device='cuda',\n    epochs=10,\n    callbacks=[es],\n    fp16=True\n)\n\nmodel.save(\"model.bin\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# augmentations taken from: https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-inference-tta\ntest_aug = albumentations.Compose([\n    albumentations.RandomResizedCrop(256, 256),\n    albumentations.Transpose(p=0.5),\n    albumentations.HorizontalFlip(p=0.5),\n    albumentations.VerticalFlip(p=0.5),\n    albumentations.HueSaturationValue(\n        hue_shift_limit=0.2, \n        sat_shift_limit=0.2,\n        val_shift_limit=0.2, \n        p=0.5\n    ),\n    albumentations.RandomBrightnessContrast(\n        brightness_limit=(-0.1,0.1), \n        contrast_limit=(-0.1, 0.1), \n        p=0.5\n    ),\n    albumentations.Normalize(\n        mean=[0.485, 0.456, 0.406], \n        std=[0.229, 0.224, 0.225], \n        max_pixel_value=255.0, \n        p=1.0\n    )\n], p=1.)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = pd.read_csv(\"../input/cassava-leaf-disease-classification/sample_submission.csv\")\nimage_path = \"../input/cassava-leaf-disease-classification/test_images/\"\ntest_images_paths = [os.path.join(image_path, x) for x in df_test.image_id.values]\n\n# dummy targets\ntest_targets = df_test.label.values\ntest_dataset = ImageDataset(\n    image_paths = test_images_paths,\n    targets=test_targets,\n    augmentations=test_aug\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# run inference 5 times\nfinal_preds = None\nfor j in range(5):\n    preds = model.predict(test_dataset, batch_size=32, n_jobs=-1)\n    temp_preds = None\n    for p in preds:\n        if temp_preds is None:\n            temp_preds = p\n        else:\n            temp_preds = np.vstack((temp_preds, p))\n    if final_preds is None:\n        final_preds = temp_preds\n    else:\n        final_preds += temp_preds\n        \nfinal_preds /= 5","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_preds","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_preds = final_preds.argmax(axis=1); final_preds","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test.label = final_preds","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}