{"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":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Import Required Libraries 📚</h1></span>","metadata":{}},{"cell_type":"code","source":"import os\nimport gc\nimport cv2\nimport math\nimport copy\nimport time\nimport random\nimport glob\nfrom matplotlib import pyplot as plt\n\n# For data manipulation\nimport numpy as np\nimport pandas as pd\n\n# Pytorch Imports\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda import amp\nimport torchvision\n\n# Utils\nimport joblib\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\n# Sklearn Imports\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\n\n# For Image Models\nimport timm\n\n# Albumentations for augmentations\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\n# For colored terminal text\nfrom colorama import Fore, Back, Style\nb_ = Fore.BLUE\nsr_ = Style.RESET_ALL\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# For descriptive error messages\nos.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:43.438396Z","iopub.execute_input":"2023-10-07T18:51:43.438754Z","iopub.status.idle":"2023-10-07T18:51:43.446112Z","shell.execute_reply.started":"2023-10-07T18:51:43.438727Z","shell.execute_reply":"2023-10-07T18:51:43.445126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Training Configuration ⚙️</h1></span>","metadata":{}},{"cell_type":"code","source":"CONFIG = {\n    \"seed\": 42,\n    \"img_size\": 512,\n    \"model_name\": \"tf_efficientnet_b0_ns\",\n    \"num_classes\": 8,\n    \"valid_batch_size\": 64,\n    \"device\": torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n}","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:43.766655Z","iopub.execute_input":"2023-10-07T18:51:43.76725Z","iopub.status.idle":"2023-10-07T18:51:43.772149Z","shell.execute_reply.started":"2023-10-07T18:51:43.767219Z","shell.execute_reply":"2023-10-07T18:51:43.770969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Set Seed for Reproducibility</h1></span>","metadata":{}},{"cell_type":"code","source":"def set_seed(seed=42):\n    '''Sets the seed of the entire notebook so results are the same every time we run.\n    This is for REPRODUCIBILITY.'''\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    # When running on the CuDNN backend, two further options must be set\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n    # Set a fixed value for the hash seed\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    \nset_seed(CONFIG['seed'])","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.012901Z","iopub.execute_input":"2023-10-07T18:51:44.013816Z","iopub.status.idle":"2023-10-07T18:51:44.019595Z","shell.execute_reply.started":"2023-10-07T18:51:44.013782Z","shell.execute_reply":"2023-10-07T18:51:44.018615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/UBC-OCEAN'\nTEST_DIR = '/kaggle/input/UBC-OCEAN/test_thumbnails'\n\nLABEL_ENCODER_BIN = \"/kaggle/input/ubc-pytorch-cnn-training-fold1of5/label_encoder.pkl\"\nBEST_WEIGHT = \"/kaggle/input/ubc-pytorch-cnn-training-fold1of5/Acc0.69_Loss0.9592_epoch20.bin\"","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.159767Z","iopub.execute_input":"2023-10-07T18:51:44.160055Z","iopub.status.idle":"2023-10-07T18:51:44.164511Z","shell.execute_reply.started":"2023-10-07T18:51:44.160031Z","shell.execute_reply":"2023-10-07T18:51:44.163277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_test_file_path(image_id):\n    return f\"{TEST_DIR}/{image_id}_thumbnail.png\"","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.288624Z","iopub.execute_input":"2023-10-07T18:51:44.289324Z","iopub.status.idle":"2023-10-07T18:51:44.29408Z","shell.execute_reply.started":"2023-10-07T18:51:44.289269Z","shell.execute_reply":"2023-10-07T18:51:44.29311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Read the Data 📖</h1>","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(f\"{ROOT_DIR}/test.csv\")\ndf['file_path'] = df['image_id'].apply(get_test_file_path)\ndf['label'] = 0 # dummy\ndf","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.569431Z","iopub.execute_input":"2023-10-07T18:51:44.569774Z","iopub.status.idle":"2023-10-07T18:51:44.585139Z","shell.execute_reply.started":"2023-10-07T18:51:44.569742Z","shell.execute_reply":"2023-10-07T18:51:44.584189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub = pd.read_csv(f\"{ROOT_DIR}/sample_submission.csv\")\ndf_sub","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.70123Z","iopub.execute_input":"2023-10-07T18:51:44.701766Z","iopub.status.idle":"2023-10-07T18:51:44.725126Z","shell.execute_reply.started":"2023-10-07T18:51:44.70173Z","shell.execute_reply":"2023-10-07T18:51:44.72375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = joblib.load( LABEL_ENCODER_BIN )","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:44.838583Z","iopub.execute_input":"2023-10-07T18:51:44.838859Z","iopub.status.idle":"2023-10-07T18:51:44.844228Z","shell.execute_reply.started":"2023-10-07T18:51:44.838836Z","shell.execute_reply":"2023-10-07T18:51:44.843248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Dataset Class</h1></span>","metadata":{}},{"cell_type":"code","source":"class UBCDataset(Dataset):\n    def __init__(self, df, transforms=None):\n        self.df = df\n        self.file_names = df['file_path'].values\n        self.labels = df['label'].values\n        self.transforms = transforms\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        img_path = self.file_names[index]\n        img = cv2.imread(img_path)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        label = self.labels[index]\n        \n        if self.transforms:\n            img = self.transforms(image=img)[\"image\"]\n            \n        return {\n            'image': img,\n            'label': torch.tensor(label, dtype=torch.long)\n        }","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:45.226073Z","iopub.execute_input":"2023-10-07T18:51:45.226616Z","iopub.status.idle":"2023-10-07T18:51:45.233398Z","shell.execute_reply.started":"2023-10-07T18:51:45.226582Z","shell.execute_reply":"2023-10-07T18:51:45.232507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Augmentations</h1></span>","metadata":{}},{"cell_type":"code","source":"data_transforms = {\n    \"valid\": A.Compose([\n        A.Resize(CONFIG['img_size'], CONFIG['img_size']),\n        A.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        ToTensorV2()], p=1.)\n}","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:45.507484Z","iopub.execute_input":"2023-10-07T18:51:45.507756Z","iopub.status.idle":"2023-10-07T18:51:45.512958Z","shell.execute_reply.started":"2023-10-07T18:51:45.507734Z","shell.execute_reply":"2023-10-07T18:51:45.511907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">GeM Pooling</h1></span>\n\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Code taken from <a href=\"https://amaarora.github.io/2020/08/30/gempool.html\">GeM Pooling Explained</a></span>\n\n![](https://i.imgur.com/thTgYWG.jpg)","metadata":{}},{"cell_type":"code","source":"class GeM(nn.Module):\n    def __init__(self, p=3, eps=1e-6):\n        super(GeM, self).__init__()\n        self.p = nn.Parameter(torch.ones(1)*p)\n        self.eps = eps\n\n    def forward(self, x):\n        return self.gem(x, p=self.p, eps=self.eps)\n        \n    def gem(self, x, p=3, eps=1e-6):\n        return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p)\n        \n    def __repr__(self):\n        return self.__class__.__name__ + \\\n                '(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + \\\n                ', ' + 'eps=' + str(self.eps) + ')'","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:45.810848Z","iopub.execute_input":"2023-10-07T18:51:45.811695Z","iopub.status.idle":"2023-10-07T18:51:45.81964Z","shell.execute_reply.started":"2023-10-07T18:51:45.811668Z","shell.execute_reply":"2023-10-07T18:51:45.818438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span><h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center\">Create Model</h1></span>","metadata":{}},{"cell_type":"code","source":"class UBCModel(nn.Module):\n    def __init__(self, model_name, num_classes, pretrained=False, checkpoint_path=None):\n        super(UBCModel, self).__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained)\n\n        in_features = self.model.classifier.in_features\n        self.model.classifier = nn.Identity()\n        self.model.global_pool = nn.Identity()\n        self.pooling = GeM()\n        self.linear = nn.Linear(in_features, num_classes)\n        self.softmax = nn.Softmax(dim=1)\n\n    def forward(self, images):\n        features = self.model(images)\n        pooled_features = self.pooling(features).flatten(1)\n        output = self.linear(pooled_features)\n        return output\n\n    \nmodel = UBCModel(CONFIG['model_name'], CONFIG['num_classes'])\nmodel.load_state_dict(torch.load( BEST_WEIGHT ))\nmodel.to(CONFIG['device']);","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:46.11481Z","iopub.execute_input":"2023-10-07T18:51:46.115083Z","iopub.status.idle":"2023-10-07T18:51:46.301446Z","shell.execute_reply.started":"2023-10-07T18:51:46.115059Z","shell.execute_reply":"2023-10-07T18:51:46.300512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Prepare Dataloaders</span>","metadata":{}},{"cell_type":"code","source":"test_dataset = UBCDataset(df, transforms=data_transforms[\"valid\"])\ntest_loader = DataLoader(test_dataset, batch_size=CONFIG['valid_batch_size'], \n                          num_workers=2, shuffle=False, pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:46.401749Z","iopub.execute_input":"2023-10-07T18:51:46.402622Z","iopub.status.idle":"2023-10-07T18:51:46.407968Z","shell.execute_reply.started":"2023-10-07T18:51:46.402586Z","shell.execute_reply":"2023-10-07T18:51:46.407055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Start Inference</span>","metadata":{}},{"cell_type":"code","source":"preds = []\nwith torch.no_grad():\n    bar = tqdm(enumerate(test_loader), total=len(test_loader))\n    for step, data in bar:        \n        images = data['image'].to(CONFIG[\"device\"], dtype=torch.float)        \n        batch_size = images.size(0)\n        outputs = model(images)\n        _, predicted = torch.max(model.softmax(outputs), 1)\n        preds.append( predicted.detach().cpu().numpy() )\npreds = np.concatenate(preds).flatten()\npred_labels = encoder.inverse_transform( preds )","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:51:46.675927Z","iopub.execute_input":"2023-10-07T18:51:46.676268Z","iopub.status.idle":"2023-10-07T18:52:00.62748Z","shell.execute_reply.started":"2023-10-07T18:51:46.676239Z","shell.execute_reply":"2023-10-07T18:52:00.626389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub[\"label\"] = pred_labels\ndf_sub.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:52:00.629781Z","iopub.execute_input":"2023-10-07T18:52:00.630352Z","iopub.status.idle":"2023-10-07T18:52:00.638717Z","shell.execute_reply.started":"2023-10-07T18:52:00.630319Z","shell.execute_reply":"2023-10-07T18:52:00.637755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub","metadata":{"execution":{"iopub.status.busy":"2023-10-07T18:52:00.640159Z","iopub.execute_input":"2023-10-07T18:52:00.640766Z","iopub.status.idle":"2023-10-07T18:52:00.659678Z","shell.execute_reply.started":"2023-10-07T18:52:00.640735Z","shell.execute_reply":"2023-10-07T18:52:00.658782Z"},"trusted":true},"execution_count":null,"outputs":[]}]}